码迷,mamicode.com
首页 > 编程语言 > 详细

c线程使用锁控制并发

时间:2019-12-16 20:55:06      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:i++   include   join   int   perror   线程   ted   increase   使用   

//
// 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\n", 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);
        }
    }
}

 

c线程使用锁控制并发

标签:i++   include   join   int   perror   线程   ted   increase   使用   

原文地址:https://www.cnblogs.com/luckygxf/p/12051203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!