MFC中的多线程 [英] Multithreading in MFC
问题描述
如果是应用程序,则使用AfxBeginthread创建线程,并使用CSemephore进行同步,如果否,则使用.工作线程的数量是不固定的(即在运行时依赖).
If the application, threads are created using AfxBeginthread and for synchronization CSemephore is used then if the no. of worker threads is not fixed (i.e dependends in runtime).
How the main thread waits for all the worker thread to finish there execution first before terminate itself?
推荐答案
您可以执行以下操作:
You could do the operations below:
- 将
CREATE_SUSPENDED
标志添加到对AfxBeginThread
- 调用
DuplicateHandle
的任何调用中,以获取先前对CWinThread对象的 m_hThread
的副本. > - 对先前调用
AfxBeginThread
- add the
CREATE_SUSPENDED
flag to any call toAfxBeginThread
- call
DuplicateHandle
to get a copy of them_hThread
of eachCWinThread
object returned by the previous call toAfxBeginThread
- call
ResumeThread
on eachCWinThread
object returned by the previous call toAfxBeginThread
返回的每个CWinThread
对象调用ResumeThread
这将确保您获得创建的每个线程的句柄(您应该将每个线程都挂起,因为CWinThread
将在线程终止时自动删除,并且您需要在完成初始化之前线程不终止)步骤).
当您要终止主线程时,请执行以下操作:
This will ensure that you get an handle to each thread you create (you should create each thread suspended because CWinThread
will auto-delete on thread termination, and you need that the thread doesn''t terminate before that you have completed your initialization steps).
When you are about to terminate your main thread, do the following:
- 对
WaitForMultipleObject
进行调用,将包含已创建线程的所有句柄的数组传递给它 - 对先前复制的每个句柄进行调用
CloseHandle
- make a call to
WaitForMultipleObject
passing it an array with all the handles of the threads you have created - call
CloseHandle
fore each handle that you have previously duplicated
这篇关于MFC中的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!