C++核心準(zhǔn)則CP.8:不要使用volatile關(guān)鍵字實(shí)現(xiàn)同步處理?

CP.8: Don't try to use?volatile?for synchronization
CP.8:不要使用volatile關(guān)鍵字實(shí)現(xiàn)同步處理
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.
不像其他語(yǔ)言,在C++中volatile不會(huì)保證原子性,不會(huì)在線程之間同步,并且不會(huì)防止指令重排(無(wú)論是編譯器還是硬件)。它沒有為并發(fā)做任何事情。
Example, bad(反面示例):
int free_slots = max_slots; // current source of memory for objectsPool* 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:
代碼中存在一個(gè)問題:在單線程程序中,這是一段完美的代碼,但是它會(huì)被兩個(gè)線程執(zhí)行,在free_slots上會(huì)發(fā)生數(shù)據(jù)競(jìng)爭(zhēng)而導(dǎo)致兩個(gè)線程可能得到同樣的值和free_slots。這(顯然)是一個(gè)壞的數(shù)據(jù)競(jìng)爭(zhēng),因此被其他語(yǔ)言訓(xùn)練過(guò)的人們可能會(huì)這樣解決這個(gè)問題:
volatile int free_slots = max_slots; // current source of memory for objectsPool* 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:
這對(duì)同步處理沒有任何作用:數(shù)據(jù)競(jìng)爭(zhēng)還在!C++實(shí)現(xiàn)數(shù)據(jù)同步的機(jī)制atomic類型:
atomicfree_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.
現(xiàn)在--操作是原子化的,而不是另一個(gè)線程可以插入操作的讀-增量-寫序列。
Alternative(其他選項(xiàng))
Use?atomic?types where you might have used?volatile?in some other language. Use a?mutex?for more complicated examples.
如果你曾經(jīng)在其他語(yǔ)言中使用過(guò)volatile關(guān)鍵字,使用原子類型。更復(fù)雜的例子可以使用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)
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp8-dont-try-to-use-volatile-for-synchronization
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
