c/c++原子操作 接口函数 自查文档

12 篇文章 0 订阅

C:

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);



bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)
type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)
type __sync_lock_test_and_set (type *ptr, type value, ...)
   将*ptr设为value并返回*ptr操作之前的值。

void __sync_lock_release (type *ptr, ...)
     将*ptr置0
#include <stdio.h>  
#include <pthread.h>  
#include <stdlib.h>  

static int count = 0;  

void *test_func(void *arg)  
{  
  int i=0;  
       for(i=0;i<20000;++i){  
         __sync_fetch_and_add(&count,1);  
  }  
  returnNULL;  
}  

int main(int argc, const char *argv[])  
{  
  pthread_tid[20];  
  int i =0;  

       for(i=0;i<20;++i){  
         pthread_create(&id[i],NULL,test_func,NULL);  
  }  

       for(i=0;i<20;++i){  
         pthread_join(id[i],NULL);  
  }  

       printf("%d\n",count);  
  return0;  
}

c++:查看
http://en.cppreference.com/w/cpp/atomic/atomic


std::atomic_char    std::atomic<char>
std::atomic_schar   std::atomic<signed char>
std::atomic_uchar   std::atomic<unsigned char>
std::atomic_short   std::atomic<short>
std::atomic_ushort  std::atomic<unsigned short>
std::atomic_int std::atomic<int>
std::atomic_uint    std::atomic<unsigned int>
std::atomic_long    std::atomic<long>
std::atomic_ulong   std::atomic<unsigned long>
std::atomic_llong   std::atomic<long long>
std::atomic_ullong  std::atomic<unsigned long long>
#include <iostream>
#include <thread>
#include <atomic>                 // modified

std::atomic_long sum = {0L};    //  modified

void fun()
{
    for(int i=0;i<100;++i)
        sum += i;
}

int main()
{
    std::cout << "Before joining,sun = " << sum << std::endl;
    std::thread t1(fun);
    std::thread t2(fun);
    t1.join();
    t2.join();
    std::cout << "After joining,sun = " << sum << std::endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Brickie-liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值