簡體   English   中英

我如何在這里添加條件變量?

[英]How would I add a condition variable here?

我正在嘗試在我的代碼中添加一個條件變量,它使用的是農業模式,但我無法理解在哪里使用它。 我以為我可以使用條件變量來暫停線程而不使用它們。 有人能告訴我一個例子或指出我正確的方向嗎?

當我嘗試時,通過檢查任務是否為空,我剛剛“等待”

Farm.cpp

void Farm::run()
{
    //list<thread *> threads;
    vector<thread *> threads;

    for (int i = 0; i < threadCount; i++)
    {
        threads.push_back(new thread([&]
        {
            while (!taskQ.empty())
            {

                taskMutex.lock();
                RowTask* temp = taskQ.front();
                taskQ.pop();
                taskMutex.unlock();
                temp->run(image_);
                delete temp;
            }

            return;
        }));
    }

    for (auto i : threads)
    {
        i->join();
    }
}

使用條件變量進行隊列實現的基本思路:

#include <queue>
#include <mutex>
#include <condition_variable>

template<typename T>
class myqueue {
    std::queue<T> data;
    std::mutex mtx_data;
    std::condition_variable cv_data;

public:
    template<class... Args>
    decltype(auto) emplace(Args&&... args) {
        std::lock_guard<std::mutex> lock(mtx_data);
        auto rv = data.emplace(std::forward<Args>(args)...);
        cv_data.notify_one(); // use the condition variable to signal threads waiting on it
        return rv;
    }

    T pop() {
        std::unique_lock<std::mutex> lock(mtx_data);
        while(data.size() == 0) cv_data.wait(lock); // wait to get a signal
        T rv = std::move(data.front());
        data.pop();
        return rv;
    }
};

暫無
暫無

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

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