__sync_原子操作

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值