使用_beginThreadex創建多線程(C語言版多線程)


_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://blog.csdn.net/laoyang360/article/details/7720656


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM