CreateThread function
Syntax
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
__drv_aliasesMem LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
Description
The CreateThread
function creates a new thread in the calling process. The new thread
begins execution at the specified start address (lpStartAddress
) and runs until
its main function returns or calls ExitThread
. The return value is a handle to the
newly created thread, which can be used by other thread functions.
Parameters
Name | Type | Description |
---|---|---|
lpThreadAttributes | LPSECURITY_ATTRIBUTES | Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle
can be inherited by child processes. NULL gives default security and non‑inheritable
handle. |
dwStackSize | SIZE_T | Initial thread stack size, in bytes. Zero uses the default size for the executable. |
lpStartAddress | LPTHREAD_START_ROUTINE | Pointer to the application-defined function to be executed by the thread. |
lpParameter | LPVOID | Pointer to a variable to be passed to lpStartAddress . |
dwCreationFlags | DWORD | Controls the creation of the thread. Use 0 for immediate start, or CREATE_SUSPENDED
to create it in a suspended state. |
lpThreadId | LPDWORD | Pointer to a variable that receives the thread identifier. Can be NULL . |
Return value
If the function succeeds, the return value is a handle to the new thread. If the function fails,
the return value is NULL
. To get extended error information, call GetLastError
.
Remarks
- The thread identifier returned through
lpThreadId
is unique only within the process; do not assume it is unique system‑wide. - Use
CloseHandle
when the thread handle is no longer needed. - Passing
CREATE_SUSPENDED
allows you to perform additional initialization before the thread runs. - Be cautious with the stack size; allocating too large of a stack can affect system resources.
Example
#include <windows.h>
#include <stdio.h>
DWORD WINAPI ThreadFunc(LPVOID lpParam) {
int *p = (int*)lpParam;
for (int i = 0; i < 5; ++i) {
printf("Thread %d: %d\n", GetCurrentThreadId(), *p + i);
Sleep(500);
}
return 0;
}
int main(void) {
int value = 100;
HANDLE hThread = CreateThread(
NULL, // default security attributes
0, // default stack size
ThreadFunc, // thread function
&value, // parameter to thread function
0, // default creation flags
NULL); // receive thread identifier
if (hThread == NULL) {
printf("CreateThread failed (%lu)\n", GetLastError());
return 1;
}
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}