我正在尝试通过 packaged_task 创建生产者-消费者模式代码如下:
test_thread9_producer1
并将test_thread9_producer2
任务推送到队列中并test_thread9_consumer1
从队列中检索任务以执行
但是,在运行时test_thread9
,它会正确执行任务但以调试错误结束:已调用 abort。我不确定为什么?任何人都可以帮助我更多地了解packaged_task
吗?
第二个问题:消费者正在循环运行,当两个生产者完成将所有任务推入队列并 完成执行队列中的所有任务时while(1)
,我想不出优雅的方式让test_thread9_consumer1
退出。test_thread9_consumer1
谁能给我一些建议?
void test_thread9()
{
std::thread t1(test_thread9_producer1);
std::thread t2(test_thread9_producer2);
std::thread t3(test_thread9_consumer1);
t1.join();
t2.join();
t3.join();
}
std::deque<std::packaged_task<int()>>task_q;
std::mutex lock9;
int factial_calc2(int in)
{
int ret = 1;
for (int i = in; i > 1; i--)
{
ret = ret*i;
}
std::lock_guard<std::mutex> locker(lock9);
std::cout << "input is " << in << "result is " << ret << std::endl;
return ret;
}
void test_thread9_producer1()
{
for (int i = 0; i < 10; i = i + 2)
{
std::lock_guard<std::mutex> locker(lock9);
std::packaged_task<int()> t1(std::bind(factial_calc2, i));
task_q.push_back(std::move(t1));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void test_thread9_producer2()
{
for (int i = 1; i < 10; i = i + 2)
{
std::lock_guard<std::mutex> locker(lock9);
std::packaged_task<int()> t1(std::bind(factial_calc2, i));
task_q.push_back(std::move(t1));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void test_thread9_consumer1()
{
std::packaged_task<int()>t;
while (1)
{
{
std::lock_guard<std::mutex> locker(lock9);
if (!task_q.empty())
{
t = std::move(task_q.front());
task_q.pop_front();
}
}
t();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}