zoukankan      html  css  js  c++  java
  • 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
    ", res);
            if (res) {
    //            fprintf(stderr, "pthread_join fail");
                perror("pthread_join fail");
            }
        }
    //    sleep(2);
        pthread_mutex_destroy(&mutex);
        printf("sum:%d
    ", 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
    ", pthread_self());
    }
    

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

  • 相关阅读:
    Less-21
    Less-22
    Less-21
    Less-20
    ssrf redis gopher
    Less19
    Less18
    Arm 系统查看、修改系统时间
    通过 grpc 请求标头发送自定义数据
    gRpc 空参数
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12285587.html
Copyright © 2011-2022 走看看