[英]how to stop running thread and resume the same thread beside create new thread?
我使用并发队列(queue_queue.h)使队列从不同线程接收元素-
每当某个线程将元素添加到并发队列时,我都会调用某个方法,该方法创建新线程以从队列中获取元素并进行处理(调用某个对此项目执行某些操作的方法)
concurrency::concurrent_queue<Item> _queue;
void handleItem(Item item)
{
// do something with item
}
// method that call every time add something to the queue - can be
// situation that the queue contain more then one item
void handleQueueItem()
{
Item item;
while (_queue.try_pop(item))
{
std::thread t1(&handleItem, item);
t1.join(); // wait till finish before handle next item.
}
}
我想以其他方式制作线程t1,这样我就不需要再创建新线程了,因为我在队列中有东西
我不知道该怎么做。
您可以使handleQueueItem
在其自己的线程中运行,并且可以连续运行,而不是在handleQueueItem
中handleQueueItem
一个线程。 看起来像
void handleItem(Item item)
{
// do something with item
}
void handleQueueItem()
{
Item item;
while (_queue.try_pop(item))
{
handleItem(item)
}
}
std::thread runner([](){ handleQueueItem(); });
您甚至可以在循环中添加一个标志,这样就可以通过添加std::atomic<bool>
变量并在循环中进行检查来停止线程
std::atomic<bool> run = true;
void handleQueueItem()
{
Item item;
while (run && _queue.try_pop(item))
{
handleItem(item)
}
}
std::thread runner([](){ handleQueueItem(); });
// later on
run = false;
runner.join();
然后您需要做的就是run = false;
使循环停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.