您好,登錄后才能下訂單哦!
C++中怎么利用volatile關鍵字實現同步處理,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
Reason(原因)
In C++, unlike some other languages, volatile does not provide atomicity, does not synchronize between threads, and does not prevent instruction reordering (neither compiler nor hardware). It simply has nothing to do with concurrency.
不像其他語言,在C++中volatile不會保證原子性,不會在線程之間同步,并且不會防止指令重排(無論是編譯器還是硬件)。它沒有為并發做任何事情。
Example, bad(反面示例):
int free_slots = max_slots; // current source of memory for objects
Pool* use()
{
if (int n = free_slots--) return &pool[n];
}
Here we have a problem: This is perfectly good code in a single-threaded program, but have two threads execute this and there is a race condition on free_slots so that two threads might get the same value and free_slots. That's (obviously) a bad data race, so people trained in other languages may try to fix it like this:
代碼中存在一個問題:在單線程程序中,這是一段完美的代碼,但是它會被兩個線程執行,在free_slots上會發生數據競爭而導致兩個線程可能得到同樣的值和free_slots。這(顯然)是一個壞的數據競爭,因此被其他語言訓練過的人們可能會這樣解決這個問題:
volatile int free_slots = max_slots; // current source of memory for objects
Pool* use()
{
if (int n = free_slots--) return &pool[n];
}
This has no effect on synchronization: The data race is still there!
The C++ mechanism for this is atomic types:
這對同步處理沒有任何作用:數據競爭還在!C++實現數據同步的機制atomic類型:
atomic<int> free_slots = max_slots; // current source of memory for objects
Pool* use()
{
if (int n = free_slots--) return &pool[n];
}
Now the -- operation is atomic, rather than a read-increment-write sequence where another thread might get in-between the individual operations.
現在--操作是原子化的,而不是另一個線程可以插入操作的讀-增量-寫序列。
Alternative(其他選項)
Use atomic types where you might have used volatile in some other language. Use a mutex for more complicated examples.
如果你曾經在其他語言中使用過volatile關鍵字,使用原子類型。更復雜的例子可以使用mutex。
See also(參照)
(rare) proper uses of volatile(volatile的正確用法)
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp200-use-volatile-only-to-talk-to-non-c-memory)
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。