开发者

Worker thread in MFC

I want to make a simple worker thread inside a same class. However, there are 3 major problems that I am facing, which are:

  1. Definition of a thread function in class header.
  2. Thread function call.
  3. Called thread function format.

I am also confused to use either AfxBeginThread or CreateThread function call to pass multiple thread pa开发者_C百科rameters. Can anyone please provide me a simple worker thread to run in MFC based on the 3 things that I have provided above?


Definition of a thread function in class header: It has to be a static member because the usual way of putting "this" in a hidden parameter doesn't work. Since you only get one parameter, you want the parameter to be a pointer to a struct, and one member of the struct can be "this" of the class instance that your static member can call.

Thread function call: Since the function that gets called is going to use MFC, it is easiest to have the caller call AfxBeginThread. Since you say the thread will be a worker thread, call the version of AfxBeginThread that is designed for worker threads (even if it doesn't matter much).

Called thread function format. MSDN describes AfxBeginThread and says what prototype must be used for the first parameter.


Ideally, you should never be using CreateThred. And if you're using MFC, you MUST use AfxBeginThread to for creating threads.

I've given some explanation here in this discussion: http://www.daniweb.com/forums/thread249210.html


CreateThread is mainly for UI Threads but is still preferred to use the second method for AfxBeginThread. Store a reference to the threads handle in the header not the thread.

HANDLE hThread;

then in source start your thread pointing to your proc:

CWinThread *pThread;
if(!(pThread = AfxBeginThread(ThreadProc, NULL, THREAD_PRIORITY_NORMAL, 0,     CREATE_SUSPENDED))) {
delete arr;
} 
::DuplicateHandle(GetCurrentProcess(), pThread->m_hThread, GetCurrentProcess(), &hThread, 0, FALSE, DUPLICATE_SAME_ACCESS);

pThread->ResumeThread();

You start it suspended so you can copy the handle to the one you have stored in header. this way you can use the stored handle to check on exitcode.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜