I have using concurrent_queue.h to have queue that receive element from different thread -
Every time some thread add element to the concurrent queue i call some method that create new thread to get element from the queue and handle it ( calling some method that do something with this item )
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.
}
}
I want to make the thread t1 in other way that i will not need to create new thread evry time i have something in the queue
I don't know how to do it.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.