1. 程式人生 > >beginThreadex建立多執行緒解讀

beginThreadex建立多執行緒解讀

_beginThreadex建立多執行緒解讀

一、需要的標頭檔案支援

 #include <process.h>         // for _beginthread()

需要的設定:ProjectàSetting-->C/C++-->User run-time library 選擇Debug Multithreaded 或者Multithreaded。即使用: MT或MTD。

原始碼如下:

 

#include <stdio.h>
#include <string> // for STL string class #include <windows.h> // for HANDLE #include <process.h> // for _beginthread() using namespace std; class ThreadX { private: int loopStart; int loopEnd; int dispFrequency; public: string threadName; ThreadX( int
startValue, int endValue, int frequency ) { loopStart = startValue; loopEnd = endValue; dispFrequency = frequency; } static unsigned __stdcall ThreadStaticEntryPoint(void * pThis) { ThreadX * pthX = (ThreadX*)pThis; // the tricky cast pthX->ThreadEntryPoint(); // now call the true entry-point-function
return 1; // the thread exit code } void ThreadEntryPoint() { for (int i = loopStart; i <= loopEnd; ++i) { if (i % dispFrequency == 0) { printf( "%s: i = %d\n", threadName.c_str(), i ); } } printf( "%s thread terminating\n", threadName.c_str() ); } }; int main() { ThreadX * o1 = new ThreadX( 0, 1, 2000 ); HANDLE hth1; unsigned uiThread1ID; hth1 = (HANDLE)_beginthreadex( NULL, // security 0, // stack size ThreadX::ThreadStaticEntryPoint, o1, // arg list CREATE_SUSPENDED, // so we can later call ResumeThread() &uiThread1ID ); if ( hth1 == 0 ) printf("Failed to create thread 1\n"); DWORD dwExitCode; GetExitCodeThread( hth1, &dwExitCode ); // should be STILL_ACTIVE = 0x00000103 = 259 printf( "initial thread 1 exit code = %u\n", dwExitCode ); o1->threadName = "t1"; ThreadX * o2 = new ThreadX( -100000, 0, 2000 ); HANDLE hth2; unsigned uiThread2ID; hth2 = (HANDLE)_beginthreadex( NULL, // security 0, // stack size ThreadX::ThreadStaticEntryPoint, o2, // arg list CREATE_SUSPENDED, // so we can later call ResumeThread() &uiThread2ID ); if ( hth2 == 0 ) printf("Failed to create thread 2\n"); GetExitCodeThread( hth2, &dwExitCode ); // should be STILL_ACTIVE = 0x00000103 = 259 printf( "initial thread 2 exit code = %u\n", dwExitCode ); o2->threadName = "t2"; ResumeThread( hth1 ); // serves the purpose of Jaeschke's t1->Start() ResumeThread( hth2 ); WaitForSingleObject( hth1, INFINITE ); WaitForSingleObject( hth2, INFINITE ); GetExitCodeThread( hth1, &dwExitCode ); printf( "thread 1 exited with code %u\n", dwExitCode ); GetExitCodeThread( hth2, &dwExitCode ); printf( "thread 2 exited with code %u\n", dwExitCode ); CloseHandle( hth1 ); CloseHandle( hth2 ); delete o1; o1 = NULL; delete o2; o2 = NULL; printf("Primary thread terminating.\n"); return 0; }

二、解釋

 

(1)如果你正在編寫C/C++程式碼,決不應該呼叫CreateThread。相反,應該使用VisualC++執行期庫函式_beginthreadex,退出也應該使用_endthreadex。如果不使用Microsoft的VisualC++編譯器,你的編譯器供應商有它自己的CreateThread替代函式。不管這個替代函式是什麼,你都必須使用。

(2)因為_beginthreadex和_endthreadex是CRT執行緒函式,所以必須注意編譯選項runtimelibaray的選擇,使用MTMTD。[MultiThreaded , Debug MultiThreaded]。

(3)_beginthreadex函式的引數列表與CreateThread函式的引數列表是相同的,但是引數名和型別並不完全相同。這是因為Microsoft的C/C++執行期庫的開發小組認為,C/C++執行期函式不應該對Windows資料型別有任何依賴。_beginthreadex函式也像CreateThread那樣,返回新建立的執行緒的控制代碼。

下面是關於_beginthreadex的一些要點:

1)每個執行緒均獲得由C/C++執行期庫的堆疊分配的自己的tiddata記憶體結構。(tiddata結構位於Mtdll.h檔案中的VisualC++原始碼中)。

2)傳遞給_beginthreadex的執行緒函式的地址儲存在tiddata記憶體塊中。傳遞給該函式的引數也儲存在該資料塊中。

3)_beginthreadex確實從內部呼叫CreateThread,因為這是作業系統瞭解如何建立新執行緒的唯一方法。

4)當呼叫CreatetThread時,它被告知通過呼叫_threadstartex而不是pfnStartAddr來啟動執行新執行緒。還有,傳遞給執行緒函式的引數是tiddata結構而不是pvParam的地址。

5)如果一切順利,就會像CreateThread那樣返回執行緒控制代碼。如果任何操作失敗了,便返回NULL。

(4)_endthreadex的一些要點:

C執行期庫的_getptd函式內部呼叫作業系統的TlsGetValue函式,該函式負責檢索呼叫執行緒的tiddata記憶體塊的地址。

然後該資料塊被釋放,而作業系統的ExitThread函式被呼叫,以便真正撤消該執行緒。當然,退出程式碼要正確地設定和傳遞。

(5)雖然也提供了簡化版的的_beginthread和_endthread,但是可控制性太差,所以一般不使用。

(6)執行緒handle因為是核心物件,所以需要在最後closehandle。

(7)更多的API:

HANDLE GetCurrentProcess();

HANDLE GetCurrentThread();

DWORD GetCurrentProcessId();

DWORD GetCurrentThreadId()。

DWORD SetThreadIdealProcessor(HANDLE hThread,DWORDdwIdealProcessor);

BOOL SetThreadPriority(HANDLE hThread,int nPriority);

BOOL SetPriorityClass(GetCurrentProcess(),  IDLE_PRIORITY_CLASS);

BOOL GetThreadContext(HANDLE hThread,PCONTEXTpContext);

BOOL SwitchToThread();

 

三、注意

 

(1)C++主執行緒的終止,同時也會終止所有主執行緒建立的子執行緒,不管子執行緒有沒有執行完畢。所以上面的程式碼中如果不呼叫WaitForSingleObject,則2個子執行緒t1和t2可能並沒有執行完畢或根本沒有執行。

(2)如果某執行緒掛起,然後有呼叫WaitForSingleObject等待該執行緒,就會導致死鎖。所以上面的程式碼如果不呼叫resumethread,則會死鎖。

 

四、為什麼用_beginthreadex而不是CreateThread?

為什麼要用C執行時庫的_beginthreadex代替作業系統的CreateThread來建立執行緒?

來源自自19997MSJ雜誌的《Win32 Q&A》欄目

你也許會說我一直用CreateThread來建立執行緒,一直都工作得好好的,為什麼要用_beginthreadex來代替CreateThread,下面讓我來告訴你為什麼。

回答一個問題可以有兩種方式,一種是簡單的,一種是複雜的。

如果你不願意看下面的長篇大論,那我可以告訴你簡單的答案:_beginthreadex在內部呼叫了CreateThread,在呼叫之前_beginthreadex做了很多的工作,從而使得它比CreateThread更安全

 轉載一部分,自己總結了一部分。


再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!希望你也加入到我們人工智慧的隊伍中來!http://www.captainbed.net