CreateThread 函式會為進程建立新的線程。 建立線程必須指定新線程要執行之程式代碼的起始位址。 一般而言,起始位址是程式代碼中定義的函式名稱(如需詳細資訊,請參閱 ThreadProc)。 此函式會採用單一參數,並傳回 DWORD 值。 進程可以有多個線程同時執行相同的函式。
以下是一個簡單的範例,示範如何建立執行本機定義函式的新線程,MyThreadFunction。
呼叫端執行緒會使用 WaitForMultipleObjects 函式來等待,直到所有工作執行緒都終止為止。 正在等候的呼叫執行緒會被封鎖;若要繼續處理,呼叫執行緒會使用 WaitForSingleObject,並等候每個工作執行緒發出其等候物件的信號。 請注意,如果您在工作線程終止之前關閉其句柄,這不會使工作線程終止。 不過,句柄將無法用於後續的函式呼叫。
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#define MAX_THREADS 3
#define BUF_SIZE 255
DWORD WINAPI MyThreadFunction( LPVOID lpParam );
void ErrorHandler(LPCTSTR lpszFunction);
// Sample custom data structure for threads to use.
// This is passed by void pointer so it can be any data type
// that can be passed using a single void pointer (LPVOID).
typedef struct MyData {
int val1;
int val2;
} MYDATA, *PMYDATA;
int _tmain()
{
PMYDATA pDataArray[MAX_THREADS];
DWORD dwThreadIdArray[MAX_THREADS];
HANDLE hThreadArray[MAX_THREADS];
// Create MAX_THREADS worker threads.
for( int i=0; i<MAX_THREADS; i++ )
{
// Allocate memory for thread data.
pDataArray[i] = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
sizeof(MYDATA));
if( pDataArray[i] == NULL )
{
// If the array allocation fails, the system is out of memory
// so there is no point in trying to print an error message.
// Just terminate execution.
ExitProcess(2);
}
// Generate unique data for each thread to work with.
pDataArray[i]->val1 = i;
pDataArray[i]->val2 = i+100;
// Create the thread to begin execution on its own.
hThreadArray[i] = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyThreadFunction, // thread function name
pDataArray[i], // argument to thread function
0, // use default creation flags
&dwThreadIdArray[i]); // returns the thread identifier
// Check the return value for success.
// If CreateThread fails, terminate execution.
// This will automatically clean up threads and memory.
if (hThreadArray[i] == NULL)
{
ErrorHandler(TEXT("CreateThread"));
ExitProcess(3);
}
} // End of main thread creation loop.
// Wait until all threads have terminated.
WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
// Close all thread handles and free memory allocations.
for(int i=0; i<MAX_THREADS; i++)
{
CloseHandle(hThreadArray[i]);
if(pDataArray[i] != NULL)
{
HeapFree(GetProcessHeap(), 0, pDataArray[i]);
pDataArray[i] = NULL; // Ensure address is not reused.
}
}
return 0;
}
DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
HANDLE hStdout;
PMYDATA pDataArray;
TCHAR msgBuf[BUF_SIZE];
size_t cchStringSize;
DWORD dwChars;
// Make sure there is a console to receive output results.
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if( hStdout == INVALID_HANDLE_VALUE )
return 1;
// Cast the parameter to the correct data type.
// The pointer is known to be valid because
// it was checked for NULL before the thread was created.
pDataArray = (PMYDATA)lpParam;
// Print the parameter values using thread-safe functions.
StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Parameters = %d, %d\n"),
pDataArray->val1, pDataArray->val2);
StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
WriteConsole(hStdout, msgBuf, (DWORD)cchStringSize, &dwChars, NULL);
return 0;
}
void ErrorHandler(LPCTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code.
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message.
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR) lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK);
// Free error-handling buffer allocations.
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
MyThreadFunction 函式可避免使用 C 執行時函式庫(CRT),因為其許多函式並非線程安全,特別是在未使用多執行緒 CRT 的情況下。 如果您想要在 ThreadProc 函式中使用 CRT,請改用 _beginthreadex 函式。
如果建立線程在新的線程之前結束時,傳遞局部變數的位址是有風險的,因為指標變得無效。 相反地,請將指標傳遞至動態配置的記憶體,或讓建立線程等候新線程終止。 您也可以使用全域變數,將數據從建立線程傳遞至新的線程。 使用全域變數時,通常需要同步處理多個線程的存取。 如需同步處理的詳細資訊,請參閱 同步處理多個線程的執行。
建立線程可以使用傳遞給 CreateThread 的參數來指定下列項目:
- 新線程句柄的安全性屬性。 這些安全性屬性包含繼承旗標,可決定子程序是否可以繼承句柄。 安全性屬性也包含安全性描述元,系統會在授與存取權之前,先對線程句柄的所有後續使用執行存取檢查。
- 新線程的初始堆疊大小。 線程的堆疊會在進程的記憶體空間中自動配置;系統會視需要增加堆疊,並在線程終止時釋放它。 如需詳細資訊,請參閱 線程堆疊大小。
- 可讓您以暫停狀態創建執行緒的創建標誌。 當暫停時,除非呼叫 ResumeThread 函式,否則線程不會執行。
您也可以呼叫 CreateRemoteThread 函式來建立線程。 調試程式會使用此函式來建立線程,該線程會在所偵錯的進程位址空間中執行。
相關主題