Threads: How to create a worker thread?
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()'.
<br>
- '_beginthreadex()'
Code:
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);
};
<br> - 'CreateThread()'
Code:
class CFoo
{
public:
CFoo()
{
m_dwThreadID = 0;
m_hThread = 0;
}
~CFoo() { CloseHandle(m_hThread); }
bool Create()
{
m_hThread = CreateThread(0,
0,
ThreadFunc,
this,
0,
&m_dwThreadID);
if(!m_hThread)
{
// Could not create thread
return false;
}
return true;
}
private:
DWORD m_dwThreadID;
HANDLE m_hThread;
static DWORD WINAPI ThreadFunc(LPVOID pvParam);
};
<br> - 'AfxBeginThread()'
Code:
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);
};
<br><br>