我将如何在此处添加条件变量
How would I add a condition variable here?
我正在尝试将一个条件变量添加到使用农业模式的代码中,但我不明白在哪里使用它。我想我可以使用条件变量在不使用线程时暂停线程。谁能给我举个例子或指出我正确的方向?
当我尝试时,通过检查任务是否为空,我只是"等待">
农场.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;
}
};
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 如何在C++中从两个单独的for循环中添加两个数组
- 在没有太多条件句的情况下,我如何避免被零除
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- 如何有条件地将元素添加到 std::array - C++11
- 有条件地使用 Boost Python 添加模块
- 有条件地添加到过载集是否合法
- 我将如何在此处添加条件变量
- 使用 QML 添加具有条件的类
- 有条件地将文件添加到项目中C++库中
- C++,在类变量中添加条件语句
- 如何有条件地添加增强 MPL
- C++,在类变量中添加条件
- 是否可以添加一些条件' boost::signal '
- 如何有条件地将函数添加到类模板中
- 我如何在精神X3中添加条件期望点
- c++预处理器添加word if条件
- c++尝试添加Peterson算法以避免共享内存中的竞争条件