簡體   English   中英

C++ 帶條件變量的生產者消費者

[英]C++ Producer-Consumer with condition variable

希望使用條件變量同步兩個線程並創建一個簡單的示例來練習。

認為我在進行同步時搞砸了,因為消費者等待來自 cv 的信號。

即使有cv.notify_one() ,但 lambda 中的行return counter != 0永遠不會被觸發,我完全不明白為什么。

#include <iostream>
#include <mutex>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;

int main(int, char**)
{
    std::mutex mx;
    std::condition_variable cv;
    int counter;

    std::thread producer( [ & ] ( )
    {
        while( true )
        {
            std::lock_guard<std::mutex> lock( mx );

            std::cout << "adding task" << std::endl;
            std::this_thread::sleep_for(1s);
            ++counter;

            cv.notify_one();
        }
    });

    std::thread consumer( [ & ] ( )
    {
        while( true )
        {
            std::unique_lock<std::mutex> lock( mx );

            cv.wait( lock, [ & ] ( )
            {
                return counter > 0;
            });

            std::cout << "Executing" << std::endl;
            std::this_thread::sleep_for(.5s);
            --counter;
        }
    });

    consumer.join();
    producer.join();

    return 0;
}

問題顯然是公平的,正如添加一行所示

std::this_thread::sleep_for(0.01s);

就在生產者獲得互斥鎖之前。

大多數操作系統不會為您提供任何關於互斥鎖的公平性保證。

有許多方法可以解決公平問題。 如果你知道如何處理這個,你可以在這里停下來。

在您的情況下,假設您的生產者和消費者實際上不需要半秒或更多時間將工作放入隊列或將工作放入隊列中,並且生產者實際上沒有無限數量的工作,那么您不需要根本不用擔心這個。 如果操作系統在競爭激烈的時刻偏愛生產者而不是消費者,隊列就會填滿(或者所有待處理的作業最終都被放入隊列),迫使生產者等待,釋放互斥量,並允許消費者輪到他們。

請注意,在具有最大隊列大小的生產者/消費者場景中,您實際上需要兩個條件變量 - 用於滿條件。

暫無
暫無

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

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