AfxBeginThread动态创建CWinThread(或派生类)线程对象,并分配相关资源.
- CWinThread* AFXAPI AfxBeginThread(CRuntimeClass* pThreadClass,
- int nPriority, UINT nStackSize, DWORD dwCreateFlags,
- LPSECURITY_ATTRIBUTES lpSecurityAttrs)
- {
- ......
- // 创建线程对象.CreateObject()函数内部有new操作符.
- CWinThread* pThread = (CWinThread*)pThreadClass->CreateObject();
- // 创建线程.
- pThread->m_pThreadParams = NULL;
- pThread->CreateThread(dwCreateFlags|CREATE_SUSPENDED, nStackSize, lpSecurityAttrs)
- return pThread;
- }
- BOOL CWinThread::CreateThread(DWORD dwCreateFlags, UINT nStackSize,
- LPSECURITY_ATTRIBUTES lpSecurityAttrs)
- {
- ... ...
- // create the thread (it may or may not start to run)
- m_hThread = (HANDLE)(ULONG_PTR)_beginthreadex(lpSecurityAttrs, nStackSize,
- &_AfxThreadEntry, &startup, dwCreateFlags | CREATE_SUSPENDED, (UINT*)&m_nThreadID);
- ... ...
- return TRUE;
- }
- UINT APIENTRY _AfxThreadEntry(void* pParam)
- {
- _AFX_THREAD_STARTUP* pStartup = (_AFX_THREAD_STARTUP*)pParam;
- CWinThread* pThread = pStartup->pThread;
- ... ...
- // forced initialization of the thread
- AfxInitThread();
- ... ...
- AfxEndThread(nResult);
- return 0; // not reached
- }
- void AFXAPI AfxEndThread(UINT nExitCode, BOOL bDelete)
- {
- ... ...
- pThread->Delete();
- // allow cleanup of any thread local objects
- AfxTermThread();
- // allow C-runtime to cleanup, and exit the thread
- _endthreadex(nExitCode);
- }
- void CWinThread::Delete()
- {
- // delete thread if it is auto-deleting
- if (m_bAutoDelete)
- delete this;
- }