谈到多线程编程,同步是一定要讲的。给个例子:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int count = 0;
#define N 100000
void* fun()
{
    int i;
    for (i = 0; i < N; ++i)
    {
        int tmp = count;
        tmp++;
        count = tmp;
    }
}

int main()
{
    pthread_t tid1, tid2;
    int ret1, ret2;
    ret1 = pthread_create(&tid1, NULL, fun, NULL);
    ret2 = pthread_create(&tid2, NULL, fun, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    printf("count = %d\n", count);
    return 0;
}
View Code

相关文章:

  • 2021-11-07
  • 2022-01-04
  • 2021-04-06
  • 2021-11-21
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
  • 2022-12-23
猜你喜欢
  • 2021-06-26
  • 2021-06-05
  • 2022-01-22
  • 2021-12-25
  • 2022-12-23
  • 2021-09-05
  • 2022-12-23
相关资源
相似解决方案