CreateThread function
Header: processthreadsapi.h
Library: Kernel32.lib
Syntax
#include <windows.h>
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
__drv_aliasesMem LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
Parameters
Name | Type | Description |
---|---|---|
lpThreadAttributes | LPSECURITY_ATTRIBUTES | Pointer to a SECURITY_ATTRIBUTES structure or NULL for default. |
dwStackSize | SIZE_T | Initial stack size, in bytes. 0 uses the default size. |
lpStartAddress | LPTHREAD_START_ROUTINE | Pointer to the application-defined function to be executed by the thread. |
lpParameter | LPVOID | Single argument passed to the thread function. |
dwCreationFlags | DWORD | Flags that control the creation of the thread. Use 0 for immediate start or CREATE_SUSPENDED to start suspended. |
lpThreadId | LPDWORD | Pointer to a variable that receives the thread identifier. May be NULL . |
Return value
If the function succeeds, the return value is a handle to the new thread. If it fails, the return value is NULL
. To get extended error information, call GetLastError
.
Remarks
- The thread created by
CreateThread
runs in the same process as the calling thread. - Close the thread handle with
CloseHandle
when it is no longer needed. - For managed code or when using the Common Language Runtime, prefer
CreateThread
over_beginthreadex
only when you do not need the CRT's thread initialization. - Use
CREATE_SUSPENDED
andResumeThread
to control start order.
Example
#include <windows.h>
#include <stdio.h>
DWORD WINAPI MyThreadFunction(LPVOID lpParam) {
int *pVal = (int*)lpParam;
printf("Thread %d running, received value %d\\n", GetCurrentThreadId(), *pVal);
return 0;
}
int main(void) {
int value = 42;
HANDLE hThread = CreateThread(
NULL, // default security attributes
0, // default stack size
MyThreadFunction, // thread function
&value, // argument to thread function
0, // default creation flags
NULL); // ignore thread identifier
if (hThread == NULL) {
printf("CreateThread failed (%lu)\\n", GetLastError());
return 1;
}
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}