评论

收藏

[C++] c线程使用锁控制并发

编程语言 编程语言 发布于:2021-08-07 11:29 | 阅读数:411 | 评论:0

//
// 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);
    }
  }
}


关注下面的标签,发现更多相似文章