#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <ctype.h>
static int count = 0;
// gcc从4.1.2提供了__sync_*系列的built-in函数,用于提供加减和逻辑运算的原子操作。
//type __sync_fetch_and_add (type *ptr, type value, ...)
//type __sync_fetch_and_sub (type *ptr, type value, ...)
//type __sync_fetch_and_or (type *ptr, type value, ...)
//type __sync_fetch_and_and (type *ptr, type value, ...)
//type __sync_fetch_and_xor (type *ptr, type value, ...)
//type __sync_fetch_and_nand (type *ptr, type value, ...)
//
//
//type __sync_add_and_fetch (type *ptr, type value, ...)
//type __sync_sub_and_fetch (type *ptr, type value, ...)
//type __sync_or_and_fetch (type *ptr, type value, ...)
//type __sync_and_and_fetch (type *ptr, type value, ...)
//type __sync_xor_and_fetch (type *ptr, type value, ...)
//type __sync_nand_and_fetch (type *ptr, type value, ...)
// 这两组函数的区别在于第一组返回更新前的值,第二组返回更新后的值。
//int8_t / uint8_t
//int16_t / uint16_t
//int32_t / uint32_t
//int64_t / uint64_t
void* test_func(void* arg){
for(int i=0;i<20000;++i){
__sync_fetch_and_add(&count,1);
// ++count;
}
return NULL;
}
int main(int argc,const char* argv[]){
pthread_t id[20];
for(int i=0;i<20;++i){
pthread_create(&id[i],NULL,test_func,NULL);
}
for(int i=0;i<20;++i){
pthread_join(id[i],NULL);
}
printf("%d\n",count); // 400000
// __sync_bool_compare_and_swap(type* ptr,type oldVal,type newVal,...)
//type __sync_val_compare_and_swap (type *ptr, type oldval, type newval, ...)
//这两个函数提供原子的比较和交换,如果*ptr == oldval,就将newval写入*ptr,
//第一个函数在相等并写入的情况下返回true.
//第二个函数在返回操作之前的值。
int num = 0;
int bRs = 0;
bRs = __sync_bool_compare_and_swap(&num,0,7);
printf("num=%d,bRs=%d\n",num,bRs); // num=7,bRs=1
int num2 = __sync_val_compare_and_swap(&num,5,9);
printf("num=%d,num2=%d\n",num,num2); //num=7,num2=7
// type __sync_lock_test_and_set (type *ptr, type value, ...)
// 将*ptr设为value并返回*ptr操作之前的值。
// void __sync_lock_release (type *ptr, ...) *ptr reset to 0
return 0;
}