簡體   English   中英

在c ++ 11中,可以使用std :: atomic在兩個線程之間傳輸非原子數據

[英]in c++11, can std::atomic be used to transmit non-atomic data between two thread

在c ++ 11中,可以使用std :: atomic在兩個線程之間傳輸非原子數據嗎? 詳細地說,以下4種語義是否都是由atomic建立的?

  1. 原子寫語句之前的所有語句(談論執行時,包括那些c ++語句生成的所有機器指令)都在原子寫之前執行。

  2. 原子讀取之后的所有語句(在談論執行時,包括那些c ++語句生成的所有機器指令)都在原子讀取之后執行。

  3. 寫入原子之前的所有其他內存寫入都將提交給主內存。

  4. 讀取原子后,所有其他所有讀取的內存將再次從主內存讀取(這意味着丟棄線程緩存)。

我在這里看到了一個例子: http : //bartoszmilewski.com/2008/12/01/c-atomics-and-memory-ordering/

但是,在該示例中,數據是原子的,所以我的問題是,如果數據不是原子的怎么辦?

這是一些代碼,顯示我想要的:

常用數據:

std::atomic_bool ready;
char* data; // or data of any other non atomic

寫線程:

data = new char[100];
data[0] = 1;
ready.store(true); // use default memory_order(memory_order_seq_cst), witch i think is the most restrict one

讀取線程:

if(ready.load()) { // use default memory_order(memory_order_seq_cst)
    assert(data[0] == 1); // both data(of type char*) and data[0~99](each of type char) are loaded
}

我認為您必須使用內存命令:

data = new char[100];
data[0] = 1;
ready.store_explicit(true, std::memory_order_release);

if(ready.load_explicit(std::memory_order_aqcuire)) {
    assert(data[0] == 1); // both data(of type char*) and data[0~99](each of type char) are loaded
}

(我不確定_explicit語法)

實際上,您的代碼是正確的,但是在這種情況下,不需要sec / cst內存順序並且acquire/release是正確的。 具有release用戶在原子寫操作之后不能對所有寫操作進行重新排序,而沒有acquire加載可以在原子加載之前進行重新排序,因此原子存儲之后所有加載都可以看到原子存儲之前的所有非原子存儲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM