第十二课:c++多线程原子类型

#include<thread>
#include<iostream>

using namespace std;
using namespace this_thread;

//原子类型

using atomic_bool = atomic<bool>;
using atomic_char   = atomic<char>;
using atomic_schar  = atomic<signed char>;
using atomic_uchar  = atomic<unsigned char>;
using atomic_short  = atomic<short>;
using atomic_ushort = atomic<unsigned short>;
using atomic_int    = atomic<int>;
using atomic_uint   = atomic<unsigned int>;
using atomic_long   = atomic<long>;
using atomic_ulong  = atomic<unsigned long>;
using atomic_llong  = atomic<long long>;
using atomic_ullong = atomic<unsigned long long>;

     /*/内存模型

    memory_order_relaxed,  //对于执行顺序不做保证  (能用)
    memory_order_consume,  //本想程中,后续原子操作必须在原子类型操作结束后在开始
    memory_order_acquire,  //本想程中,后续原子读操作必须在原子类型操作结束后在开始
    memory_order_release,  //本想程中,后续原子写操作必须在原子类型操作结束后在开始  (能用)
    memory_order_acq_rel,  //memory_order_release和memory_order_acquire综合
    memory_order_seq_cst   //全部读写按顺序来做  (能用)

    强顺序:代码顺序和执行顺序是一样
    弱顺序:代码执行顺序会被处理器做调整

    atomic<int> iNum(2);
    iNum.store(2, memory_order::memory_order_relaxed);     //写操作
    iNum.load(memory_order::memory_order_relaxed);         //读操作
    iNum.exchange(2, memory_order::memory_order_relaxed);  //修改操作

*/


atomic<int> a;
atomic<int> b;

void threadFunc()
{
    int t = 0;
    a = t;
    b = 1;  //这行代码不依赖上面的任何,执行过程,b = 1 可能比上面的代码执行要快,更早

}


void setValut()
{
    int t = 1;
    a.store(t, memory_order::memory_order_release);   // a = t
    b.store(2, memory_order::memory_order_relaxed);   // b = 1
}


void printfAtomic()
{
    cout << a << " " << endl; 
    cout <<b.exchange(111, memory_order::memory_order_release)<< " " << endl;
   
}

int main()
{

    thread t1(setValut);
    thread t2(printfAtomic);

    t1.join();
    t2.join();

    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值