PostHeaderIcon Win32 Worker Thread without UI

When you want to create a worker thread with Win32 API.

first,define a function like this: UNIT ThreadFunc(LPVOID pParam) ,the detail of it you can find on MSDN;

second,call the ThreadFunc with the Win32API – AfxBeginThread;

last,put the AfxBeginThread API in the right place.

You can find the AfxBeginThread API declarations on MSDN:

CWinThread* AfxBeginThread(
   AFX_THREADPROC pfnThreadProc,
   LPVOID pParam,
   int nPriority = THREAD_PRIORITY_NORMAL,
   UINT nStackSize = 0,
   DWORD dwCreateFlags = 0,
   LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL
);
CWinThread* AfxBeginThread(
   CRuntimeClass* pThreadClass,
   int nPriority = THREAD_PRIORITY_NORMAL,
   UINT nStackSize = 0,
   DWORD dwCreateFlags = 0,
   LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL
);

The first form of AfxBeginThread creates a worker thread. The second form creates a user-interface thread[From MSDN].


Now In Action:

No1, We create a MFC dialog program, as follows:

No2,define a thread function – Number Counter:

UINT WorkerThreadSample(LPVOID pParam)
{
	int threadNo=(int)pParam;
	for (int i=0;i<100;++i)
	{
		TRACE(_T("WorkerThread_%d: %d\r\n"),threadNo,i);
		Sleep(100);
	}
	return 0;
}

No3,call the Number Counter thread function with Win32 API – AfxBeginThread:

AfxBeginThread(WorkerThreadSample,(LPVOID)threadNo);

No4,put No3 in the right place of your program:

void CSingleThreadDlg::OnCreateThread()
{
	static int threadNo=1;
	AfxBeginThread(WorkerThreadSample,(LPVOID)threadNo);
	++threadNo;
}

No5,Test it:

output

Summary: this demo(worker thread) without UI,I’ll intro UI worker thread in next article.

15,350 views

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Copyright © 2010 - C++ Technology. All Rights Reserved.

Powered by Jerry | Free Space Provided by connove.com