等待任务在线程池中完成 [英] Wait for tasks to get completed in threadpool

查看:307
本文介绍了等待任务在线程池中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中创建了一个线程池,它将所有任务存储在队列中。线程池启动n从队列中取任务的线程数,处理每个任务,然后从队列中删除任务。

I have created a thread pool in C++ which stores all tasks in a queue. Thread pool start n number of threads which takes tasks from queue , process each task and then delete tasks from queue.

现在,我想等待所有任务完成。检查空队列以完成任务可能不起作用,任务可以被给予每个线程,并且队列可以被清空,但仍然任务可以处于处理模式。

Now , I want to wait till all tasks get completed. Checking for empty queue for completion of tasks may not work as , task can be given to each thread and queue can be emptied but still the tasks can in processing mode.

I我不知道如何等待所有的任务完成。这是一个设计问题。任何建议?

I am not getting idea how to wait for all the tasks completion.This is a design problem. Any suggestions?

推荐答案

您需要等待所有主题完成,还是只需要检查?

Do you need to wait for all threads to finish, or do you just need to check?

如果你只需要检查,你可以有一个变量存储当前正在执行的任务的数量, InterlockedIncrement 一个线程的开始,然后 InterlockedDecrement 它在结束。

If you just need to check, you can have a variable that stores the number of currently executing tasks, and InterlockedIncrement it at the beginning of a thread, then InterlockedDecrement it at the end.

如果你需要等待,一个少量的线程,每个线程都可以有自己的手动复位事件,当 ResetEvent 当线程启动时, SetEvent 当它完成。然后对所有事件只需 WaitForMultipleObjects

If you need to wait, and you have a small number of threads, each thread can have its own manual reset event that you ResetEvent when the thread starts and SetEvent when it finishes. Then just WaitForMultipleObjects for all events.

这篇关于等待任务在线程池中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆