1 #include <stdio.h> 2 #include <pthread.h> 3 #include <stdlib.h> 4 5 static int count = 0; 6 7 void *test_func(void *arg) 8 { 9 int i=0; 10 for(i=0; i < 20000; i++) { 11 __sync_fetch_and_add(&count,1); 12 //count++; 13 } 14 return NULL; 15 } 16 17 int main(int argc, const char *argv[]) 18 { 19 pthread_t id[20]; 20 int i = 0; 21 22 for(i=0; i < 20; i++) { 23 pthread_create(&id[i],NULL,test_func,NULL); 24 } 25 26 for(i=0; i<20; ++i) { 27 pthread_join(id[i],NULL); 28 } 29 30 printf("%d ",count); 31 return 0; 32 }
参考链接:https://blog.csdn.net/youfuchen/article/details/23179799
https://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html