• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c使用mutex同步

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void increase();

int sum = 0;

pthread_mutex_t mutex;

int main() {
    // init mutex
    pthread_mutex_init(&mutex, NULL);
    pthread_t threads[4];
    for (int i = 0; i < sizeof(threads) / sizeof(threads[0]); i++) {
        pthread_create(&threads[i], NULL, increase, NULL);
    }

    for (int i = 0; i < sizeof(threads) / sizeof(threads[0]); i++) {
        void *joinstatus;
        int res = pthread_join(threads[i], &joinstatus);
        printf("res:%d\n", res);
        if (res) {
//            fprintf(stderr, "pthread_join fail");
            perror("pthread_join fail");
        }
    }
//    sleep(2);
    pthread_mutex_destroy(&mutex);
    printf("sum:%d\n", sum);
    return 0;
}

void increase() {
    for (int i = 0; i < 10000; i++) {
        pthread_mutex_lock(&mutex);
        sum++;
        pthread_mutex_unlock(&mutex);
    }
    printf("t_id:%u\n", pthread_self());
}

pthread_joint开始传的&thread,指针类型,编译和运行都没有报错,函数返回3。改成pthread_t类型的可以了  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#TEXTBOX中只允许输入数字和一个小数点发布时间:2022-07-18
下一篇:
C#实现ADSL自动断网和拨号(适用于拨号用户)发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap