谈到多线程编程,同步是一定要讲的。给个例子:
#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; }