在c ++中使用std :: atomic <bool>的比较和读/写操作?

时间:2018-03-11 21:30:18

标签: c++ c++11

假设有callvirt个帖子; C#: ((IFoo)foo).Bar(); ; C: (*(foo->TypeHandle->InterfaceMap[0x30]))(foo) mov ecx,edi ; move "foo" pointer into ecx mov eax,dword ptr [ecx] ; Dereference to place MethodTable into eax mov eax,dword ptr [eax+0Ch] ; Dereference to interface map address ; (offset 12 is constant for that version of ; the CLR) mov eax,dword ptr [eax+30h] ; move the ifc impl start slot into eax ; (30h is discovered at time of JIT by ; examining the loaded type hierarchy) call dword ptr [eax] ; call foo.Bar 2,我们将在这些threadA中使用threadB数据类型。所以现在我们有一些关键部分如下:

我的全局变量(线程同时访问它):

std::atomic<bool>

threadA:

threads

threadB:

std::atomic<bool> flag;

任何方式,我知道void *threadA(void *arg) { bool ttt = true; if(flag == true) // comparison operator == // do something // something to do flag = false; // assign a avalue ttt = flag; // read operation return 0; } 不像普通的数据类型是自由竞赛,但我想确定这些:

    使用void *threadB(void *arg) { bool m = true; if(flag == true) // comparison operator == flag = false; // something to do flag = true; // assign a value m = !flag; // read operation return 0; } std::atomic<>==代替(例如)assignment或交换语句时,
  • 会有任何问题吗?
  • 是否可能发生任何问题,例如在read/write读取或写入时std::atomic_load出现问题?
  • 在任何 CPU 架构的平台上绝对安全吗?我的意思是(便携式代码)。因为memory在某些 X86 架构中不需要?

我只想使用flag功能代替atomic<bool>

1 个答案:

答案 0 :(得分:1)

  使用==assignmentread/write代替(例如)std::atomic_loadexchange语句时,

会有什么问题?

operator==std::atomic<T>T一起使用时,它首先使用最强的内存排序{{1}调用atomic<T>::operator T()load原子值}。接下来,使用std::memory_order_seq_cst。这个序列不是原子的。这意味着当比较实际发生时operator==(T, T)可能已经发生变化。

  

只想使用原子特征而不是std::atomic<T>

你可以使用std::atomic::compare_exchange_weak实现一个带有原子的自旋锁(有一个例子),但它不能像mutex一样让线程处于休眠状态。