我将如何在此处添加条件变量

How would I add a condition variable here?

本文关键字:添加 条件 变量      更新时间:2023-10-16

我正在尝试将一个条件变量添加到使用农业模式的代码中,但我不明白在哪里使用它。我想我可以使用条件变量在不使用线程时暂停线程。谁能给我举个例子或指出我正确的方向?

当我尝试时,通过检查任务是否为空,我只是"等待">

农场.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;
    }
};