問題描述
如何在創建新線程的同時停止運行線程並恢復同一個線程? (how to stop running thread and resume the same thread beside create new thread?)
我使用 concurrent_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,這樣我每次隊列中有東西時都不需要創建新線程
我不知道該怎麼做。
參考解法
方法 1:
Instead of spinning up a thread in handleQueueItem
, you can make handleQueueItem
run in its own thread and it will run continuously. That would look like
void handleItem(Item item)
{
// do something with item
}
void handleQueueItem()
{
Item item;
while (_queue.try_pop(item))
{
handleItem(item)
}
}
std::thread runner([](){ handleQueueItem(); });
You can even add a flag to the loop so you can stop the thread by adding a std::atomic<bool>
variable and checking it in the loop like
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();
And then all you need to do is run = false;
to have the loop stop.
(by Yanshof、NathanOliver)