C++中怎么利用volatile關(guān)鍵字實(shí)現(xiàn)同步處理,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
10年積累的成都做網(wǎng)站、網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先做網(wǎng)站后付款的網(wǎng)站建設(shè)流程,更有海興免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
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不會(huì)保證原子性,不會(huì)在線程之間同步,并且不會(huì)防止指令重排(無論是編譯器還是硬件)。它沒有為并發(fā)做任何事情。
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:
代碼中存在一個(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),因此被其他語言訓(xùn)練過的人們可能會(huì)這樣解決這個(gè)問題:
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:
這對(duì)同步處理沒有任何作用:數(shù)據(jù)競(jìng)爭(zhēng)還在!C++實(shí)現(xiàn)數(shù)據(jù)同步的機(jī)制atomic類型:
atomic
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.
現(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)在其他語言中使用過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)
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。