I want to implement a way to schedule a task later. The interface will look like JavaScript setTimeout(function, milliseconds) .
In my application, certain resources belong to a thread. To avoid race conditions, they should always be accessed from the same thread. If other threads want to access the resource, they must send the task object to the resource stream.
So, I need to solve two problems:
- send task to stream
- Call delay
The first problem is quickly fixed with a non-queue lock that has a resource flow on the consumption side. (I use TBB concurrent_bounded_queue.) The second problem, however, is not so obvious to me. I can think of two strategies:
- Run a new thread for each task. This thread will reset the required delay, and then send the task in a parallel queue.
- Start only one thread that starts a loop that iterates through the scheduled tasks and calls them if their timeout has expired.
I experimented with both approaches, and I am inclined to the first, because it is simple and reliable, and the second, as a rule, is more prone to subtle errors. The first approach delegates this to the OS thread scheduler.
However, the first solution creates many short-lived threads, while I usually hear the recommendation of reusing threads.
c ++ multithreading
Stackedcrooked
source share