zoukankan      html  css  js  c++  java
  • c线程使用锁控制并发

    //
    // Created by gxf on 2019/12/16.
    //
    #include <stdlib.h>
    #include <stdio.h>
    #include <pthread.h>
    
    void increase_num();
    
    int sharedi=0;
    
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    
    int main(){
        pthread_t t1, t2, t3;
        pthread_create(&t1, NULL,increase_num, NULL);
        pthread_create(&t2, NULL,increase_num, NULL);
        pthread_create(&t3, NULL,increase_num, NULL);
    
        pthread_join(t1, NULL);
        pthread_join(t2, NULL);
        pthread_join(t3, NULL);
    
        printf("shared:%d
    ", sharedi);
        return 0;
    }
    
    void increase_num(){
        for (int i = 0; i < 100000; i++){
            if (pthread_mutex_lock(&mutex) != 0) {
                perror("mutex lock fail");
                exit(EXIT_FAILURE);
            }
            long temp = sharedi;
            temp += 1;
            sharedi = temp;
            if (pthread_mutex_unlock(&mutex)) {
                perror("mutex unlock fail");
                exit(EXIT_FAILURE);
            }
        }
    }
  • 相关阅读:
    阿里云nginx创建多站点
    linux 卸载php mysql apache
    centos php环境搭建
    jquery simple modal
    nodejs 安装express
    nodejs fs.open
    nodejs supervisor
    nodejs 运行
    nodejs shell
    PHP array_pad()
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12051203.html
Copyright © 2011-2022 走看看