1. 程式人生 > >Windows中建立執行緒的函式:CreateThread()

Windows中建立執行緒的函式:CreateThread()

Windows中建立執行緒的函式:CreateThread();該函式的原型宣告如下:

HANDLE CreateThread(

LPSECURITY_ATTRIBUTES lpThreadAttributes,

DWORD dwStackSize,

LPTHREAD_START_ROUTINE lpStartAddress,

LPVOID lpParameter,

DWORD dwCreationFlags,

LPDWORD lpThreadId); 

Parameters:

lpThreadAttributes

Ignored. Must be NULL.

NULL表示執行緒採用預設的安全性,我們進行程式設計是通常將該引數設定為NULL。

 

dwStackSize

Ignored. The default stack size for a thread is determined by the linker setting /STACK.

設定執行緒初始棧的大小,單位是位元組。系統會把該引數四捨五入為最接近的頁面大小。關於頁面的概念,可以通過上網進行查詢。該引數設定為0,表示預設採用與呼叫該函式的執行緒相同的棧空間大小。

 

lpStartAddress

Long pointer to the application-defined function of type LPTHREAD_START_ROUTINE to be executed by the thread and represents the starting address of the thread. For more information on the thread function, see ThreadProc.

該引數為新執行緒的起始地址,該引數不能省略,其實,起始地址就是函式的名字。

 

lpParameter

Long pointer to a single 32-bit parameter value passed to the thread.

執行緒函式的命令列引數,如果沒有命令列引數,該值應設定為NULL。

 

dwCreationFlags

Specifies flags that control the creation of the thread. 

執行緒建立標誌,具體設定見下表:

Value

Description

                CREATE_SUSPENDED

The thread is created in a suspended state, and will not run until theResumeThread function is called.

                0

The thread runs immediately after creation.

 

lpThreadId

Long pointer to a 32-bit variable that receives the thread identifier.

If this parameter is NULL, the thread identifier is not returned. 

       LpThreadId是一個返回值,其值為執行緒ID,

      該函式的返回值為執行緒控制代碼,控制代碼是使用者實現對執行緒操作的橋樑,執行緒ID 是執行緒在系統中存在的唯一標示。如果兩個執行緒返回的ID相同,這說明兩個執行緒是同一個執行緒。當然,在windows 2000和Windows NT4下,我們可以將該引數設定為NULL,標示對執行緒的ID不感興趣,即不利用執行緒ID進行一定的操作。

      執行緒的控制代碼並不是執行緒的唯一標識,執行緒的控制代碼只是用來訪問該執行緒的的一個32位值,儘管相同的控制代碼一定標識同一執行緒,但同一執行緒可能擁有兩個開啟的控制代碼,因此,不能用控制代碼來區分兩個執行緒是否是同一執行緒