开发者

CWinThread Enquiries (MFC)

开发者 https://www.devze.com 2023-02-15 15:16 出处:网络
I have a very simple question about how CWinThread works and where is the entry point everytime I called ResumeThread(). I\'m looking for an entry that looks similar as \"main\" function where I can p

I have a very simple question about how CWinThread works and where is the entry point everytime I called ResumeThread(). I'm looking for an entry that looks similar as "main" function where I can perform some operations and branches.

I'm also wondering how to end or kill running threads at any point from different thread. Where should I put AfxEndThread()? or simply call pThread->ExitInstance()?

My last question is, if i want to make multiple threads开发者_运维知识库, how do I organize them in Standard Template Library (STL) using vector?

Thank you.


I think you have a fundamental misunderstanding of how threads are meant to be used.

Functions like SuspendThread() and ResumeThread() and functions to terminate threads are not how you are meant to control threads. In fact, the Windows API functions that SuspendThread() and ResumeThread() map onto are documented as being intended for debuggers. It would be nice if the MFC documentation also said this, but it doesn't.

If you use SuspendThread() to pause a thread then you've no idea what it is doing when you pause it. If it just happens to hold a lock then you can deadlock your program.

The normal mechanism for controlling threads is to use event objects to signal to the thread that you want it to pause or resume. The reason event objects are used rather than simple boolean flags, say, is that events can be waited on. This means that you can put a thread into a non-busy state, not consume CPU and have it start-up when signalled by the controlling thread.

Regarding termination, it is absolutely a last resort to call TerminateThread(). Doing so leaves your synchronisation objects (e.g. critical sections, mutexes etc.) in an undefined state and is highly likely to lead to horrible defects in your software. Again for termination you should signal to a thread that you wish it to quit, and then wait until it has done so.


The primary entry point for a class derived from CWinThread is the virtual Run() function. However, there is also an InitInstance() function which is called beforehand, and an ExitInstance() function called afterwards.

You should never call ExitInstance() yourself. Instead, call AfxEndThread, or just return from Run().

If you really want to put your threads in a std::vector<> then use a pointer as the class is not copyable, and the instance is deleted automatically by MFC when the thread exits.

Edit: As David pointed out, you generally don't want to use SuspendThread and ResumeThread in application code. Start your thread with AfxBeginThread if you're using MFC.

0

精彩评论

暂无评论...
验证码 换一张
取 消