簡體   English   中英

std :: mutex是否足以用於線程之間的數據同步

[英]Is std::mutex sufficient for data synchronization between threads

如果我有一個多線程正在寫入和讀取的全局數組,並且我想確保這個數組在線程之間保持同步,那么使用std :: mutex就足夠了,如下面的偽代碼所示? 我遇到了這個資源 ,這讓我覺得答案是肯定的:

相互排除鎖(例如std :: mutex或atomic spinlock)是發布 - 獲取同步的一個示例:當線程A釋放鎖並由線程B獲取鎖時,發生在關鍵部分(發布之前)的所有內容在線程A的上下文中,必須對執行相同臨界區的線程B(獲取之后)可見。

我仍然對其他人的意見感興趣。

float * globalArray;
std::mutex globalMutex;

void method1() 
{
    std::lock_guard<std::mutex> lock(globalMutex);
    // Perform reads/writes to globalArray
}

void method2() 
{
    std::lock_guard<std::mutex> lock(globalMutex);
    // Perform reads/writes to globalArray
}

main() 
{
    std::thread t1(method1());
    std::thread t2(method2());
    std::thread t3(method1());
    std::thread t4(method2());
    ...
    std::thread tn(method1());
}

這正是互斥體的用途。 盡量不要超過必要的時間來保持它們以最小化爭用成本。

暫無
暫無

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

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