http://blog.163.com/xychenbaihu@yeah/blog/static/1322296552013373236132/
https://www.cnblogs.com/wzjhoutai/p/6838104.html
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<pthread.h>
int count = 0;
void *func_cas(void*arg)
{
int i=0;
int temp = 0;
for(i = 0;i < 20000;i++)
{
while(1)
{
temp = count;
if(__sync_bool_compare_and_swap(&count, temp, temp+1))
break;
}
}
}
void *func(void*arg)
{
int i=0;
for(i = 0;i < 20000;i++)
{
count++;
}
}
int main()
{
pthread_t id[10];
int i=0;
for(i=0 ;i< sizeof(id)/sizeof(id[0]);i++)
{
pthread_create(&id[i],NULL,func_cas,NULL);
}
for(i=0 ;i< sizeof(id)/sizeof(id[0]);i++)
{
pthread_join(id[i],NULL);
}
printf("count = %d\n",count);
count = 0;
for(i=0 ;i< sizeof(id)/sizeof(id[0]);i++)
{
pthread_create(&id[i],NULL,func,NULL);
}
for(i=0 ;i< sizeof(id)/sizeof(id[0]);i++)
{
pthread_join(id[i],NULL);
}
printf("\ncount = %d\n",count);
}