Ensuring task execution order in threadpool

后端 未结 17 939
情深已故
情深已故 2020-12-12 11:54

I have been reading about the thread-pool pattern and I can\'t seem to find the usual solution for the following problem.

I sometimes want tasks to be executed serial

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 12:48

    Thread pools are good for cases where the relative order of the tasks doesn't matter, provided they all get done. In particular, it must be OK for them all to be done in parallel.

    If your tasks must be done in a specific order, then they are not suitable for parallelism, so a thread pool is not appropriate.

    If you want to move these serial tasks off the main thread, then a single background thread with a task queue would be appropriate for those tasks. You can continue to use a thread pool for the remaining tasks which are suitable for parallelism.

    Yes, it means you have to decide where to submit the task depending on whether it is an in-order task or a "may be parallelized" task, but this is not a big deal.

    If you have groups that must be serialized, but which can run in parallel with other tasks then you have multiple choices:

    1. Create a single task for each group, which does the relevant group tasks in order, and post this task to the thread pool.
    2. Have each task in a group explicitly wait for the previous task in the group, and post them to the thread pool. This requires that your thread pool can handle the case where a thread is waiting for a not-yet-scheduled task without deadlocking.
    3. Have a dedicated thread for each group, and post group tasks on the appropriate message queue.

提交回复
热议问题