CreateThread函數(shù)是Windows操作系統(tǒng)提供的用于創(chuàng)建線程的函數(shù),在C語(yǔ)言中使用。
其函數(shù)原型為:
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
參數(shù)說(shuō)明:
CreateThread函數(shù)返回一個(gè)線程的句柄(HANDLE類型),可以通過(guò)此句柄對(duì)線程進(jìn)行操作。
使用CreateThread函數(shù)創(chuàng)建線程的基本步驟如下:
示例代碼:
#include <stdio.h>
#include <windows.h>
DWORD WINAPI threadFunc(LPVOID lpParam) {
printf("Hello from thread!\n");
return 0;
}
int main() {
HANDLE hThread;
DWORD threadId;
hThread = CreateThread(NULL, 0, threadFunc, NULL, 0, &threadId);
if (hThread == NULL) {
printf("Failed to create thread.\n");
return 1;
}
printf("Thread created with ID: %d\n", threadId);
// ... 其他操作
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
以上示例代碼中,調(diào)用CreateThread函數(shù)創(chuàng)建了一個(gè)線程,并通過(guò)WaitForSingleObject函數(shù)等待線程結(jié)束。