评论

收藏

[C++] c使用mutex同步

编程语言 编程语言 发布于:2021-08-07 14:05 | 阅读数:346 | 评论:0

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


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