簡體   English   中英

c++ wait_for 方法mutex 中的謂詞內容是否受保護?

[英]Is the content of a predicate in c++ wait_for method mutex protected or not?

假設, countMe是一個全局變量,我同時啟動 10 個線程到這個 while 循環,變量countMe mutex 是否在謂詞中受到保護? 我認為是因為當代碼到達 wait_for 它解鎖並釋放鎖時,變量 countMe 不受互斥保護。 我對嗎?

while (true)
{
    std::unique_lock<std::mutex> lock(mtx_kill);
    cv_kill.wait_for(lock, 500ms, [&]() {++countMe; return killFlag; });

    if (killFlag)
    {
        break;
    }
}

我對嗎?

不,你錯了。

我認為是因為當代碼到達 wait_for 時它會解鎖鎖,變量 countMe 不受互文保護。

不,當 lambda 被評估時,互斥量處於鎖定的 state 中。 保證。

cppreference.com用wait_until 描述了wait_for的謂詞版本, 描述如下

while (!stop_waiting()) {
    if (wait_until(lock, timeout_time) == std::cv_status::timeout) {
        return stop_waiting();
    }
}

請注意,互斥量的初始 state 是它已鎖定。 此處稱為“stop_waiting”的謂詞總是在互斥鎖處於鎖定 state 時調用。

您可以將wait_for視為一個無謂詞的wait ,將額外的謂詞檢查視為一個離散的、單獨的步驟。 wait返回后,互斥鎖被重新鎖定,這發生在謂詞 lambda 執行之前。 如果它投反對票,互斥量將再次以原子方式解鎖,並再次等待條件變量。

PS 上面的討論假定你的countMe總是在其他地方被訪問,並且持有相同的鎖。 這是您的問題假定的,但只是正式指出。

暫無
暫無

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

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