c使用mutex同步

#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类型的可以了  

posted on 2020-02-08 23:04  luckygxf  阅读(704)  评论(0编辑  收藏  举报

导航