#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;
}
第十二课:c++多线程原子类型
最新推荐文章于 2024-10-31 09:04:32 发布