我将如何在此处添加条件变量?
How would I add a condition variable here?
我正在尝试向使用耕作模式的代码添加条件变量,但我不知道在哪里使用它。我想我可以使用条件变量在线程未被使用时暂停它们。谁能给我举个例子或给我指明正确的方向?
当我尝试时,通过检查任务是否为空,我刚刚离开 "waiting"
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;
}
};
我正在尝试向使用耕作模式的代码添加条件变量,但我不知道在哪里使用它。我想我可以使用条件变量在线程未被使用时暂停它们。谁能给我举个例子或给我指明正确的方向?
当我尝试时,通过检查任务是否为空,我刚刚离开 "waiting"
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;
}
};