Q: How to create a worker thread?
A: There are several ways to create a worker thread:
- '_beginthread()' (C run-time library)
- '_beginthreadex()' (C run-time library)
- 'CreateThread()' (Win32 API)
- 'CreateRemoteThread()' (Win32 API)
- 'AfxBeginThread()' (MFC)
The following samples will show the creation of a thread using the three functions '_beginthreadex()', 'CreateThread()' and 'AfxBeginThread()'.
- '_beginthreadex()'
class CFoo
{
public:
CFoo()
{
m_uiThreadID = 0;
m_ulThreadHandle = 0;
}
bool Create()
{
m_ulThreadHandle = _beginthreadex(0,
0,
ThreadFunc,
this,
0,
&m_uiThreadID);
if(!m_ulThreadHandle)
{
// Could not create thread
return false;
}
return true;
}
private:
unsigned int m_uiThreadID;
unsigned long m_ulThreadHandle;
static unsigned int __stdcall ThreadFunc(void *pvParam);
};
- 'AfxBeginThread()'
class
CMyDialog : public CDialog
{
public:
CMyDialog(CWnd* pParent = NULL)
: CDialog(CMyDialog::IDD, pParent)
{
m_pThread = 0;
}
bool Create()
{
m_pThread = AfxBeginThread(ThreadFunc, this);
if(!m_pThread)
{
// Could not create thread
return false;
}
return true;
}
private:
CWinThread *m_pThread;
static UINT ThreadFunc(LPVOID pvParam);
};
Note: Most of the material in this article is taken from codeguru.com
Recommended Reading :