0%

atomic operation in C11 and C++11

在關注C++11的食嘔,發現C11標準也在2011年同時發佈。
目前C11的支持肚兜不太夠,因此我是用Pelles C測試。
C11的寫法,相關的資料可以參考[Threads in the new ISO C Standard from 2011](Threads in the new ISO C Standard from 2011)。

1
2
3
4
5
6
7
#include <stdatomic.h>
int main(int argc, char *argv[])
{
_Atomic(int) i = ATOMIC_VAR_INIT(0); // atomic_init(&i, 0);
atomic_fetch_add_explicit(&i, 1, memory_order_relaxed);
return 0;
}

C++11的寫法,可以參考Atomic operations library

1
2
3
4
5
6
7
8
#include <atomic>
std::atomic<int> sharedValue(0); // std::atomic_init(&sharedValue, 0);
// std::atomic<int> sharedValue = ATOMIC_VAR_INIT(0); 跟上面效果一樣
int main()
{
sharedValue.fetch_add(1, memory_order_relaxed);
return 0;
}

看起來峎像,只是C++11的寫法是使用template來表示。不過更具彈性,如果你有一個HugeObject的類別,你可以透過atomi<HugeObject>來達成Atomic operation,裡面用個Mutex來保護。

至於C11跟C++11的Memory Model從Java那邊得到啟發而修改,那就是另外一個大故事了。有空在寫。