I am trying to packaged_task to create a producer-consumer patten
code is as following :
test_thread9_producer1
and test_thread9_producer2
push task into a queue
and test_thread9_consumer1
retrieve task from the queue to execute
However when running test_thread9
, it executes task correctly but finished with debug error : abort has been called. I'm not sure why ? Can anyone help me get more understanding of packaged_task
?
A second issue: consumer is running with while(1)
loop, I can not think of graceful way
to let test_thread9_consumer1
exit when two producers finished pushing all tasks into queue and test_thread9_consumer1
finished executing all tasks in the queue. Can anyone give me some suggestion ?
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));
}
}