CreateThread Function

Creates a thread to execute within the virtual address space of the calling process.

Syntax


LPVOID CreateThread(
  LPSECURITY_ATTRIBUTES lpThreadAttributes,
  SIZE_T              dwStackSize,
  LPTHREAD_START_ROUTINE  lpStartAddress,
  LPVOID              lpParameter,
  DWORD               dwCreationFlags,
  LPDWORD             lpThreadId
);
            

Parameters

Parameter Description
lpThreadAttributes A pointer to a SECURITY_ATTRIBUTES structure that specifies the security descriptor for the new thread. If this parameter is NULL, the thread gets a default security descriptor that has access to the same job object as the process.
dwStackSize The initial size, in bytes, of the stack for the new thread. If this parameter is 0, the size of the stack is the same as the default size for the process.
lpStartAddress A pointer to the application-defined function of type LPTHREAD_START_ROUTINE that represents the starting address of the thread to be executed.
lpParameter The argument to be passed to the thread function.
dwCreationFlags Flags that control the creation of the thread. This parameter can be 0 or any of the following values:
  • CREATE_SUSPENDED: The thread is created in a suspended state. Use the ResumeThread function to run the thread.
  • STACK_SIZE_PARAM_IS_A_RESERVATION: If this flag is specified, dwStackSize specifies the size of the stack allocation. If this flag is not specified, dwStackSize specifies the reserve and commit size.
  • 0x00000000: The thread runs immediately.
lpThreadId A pointer to a 32-bit value that receives the thread identifier of the new thread. If this parameter is NULL, the thread identifier is not returned.

Return Value

If the function succeeds, the return value is a handle to the new thread. Each thread has a unique handle. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The thread created by CreateThread has access to the same address space as the calling process. The thread can read from and write to the same data segments as the calling process.

Threads created with CREATE_SUSPENDED are not resumed until ResumeThread is called.

Note: A thread created with CREATE_SUSPENDED and never resumed will not terminate and will not be cleaned up by the system. You must explicitly resume the thread and then terminate it or allow it to complete.
Tip: For more complex thread management scenarios, consider using the Windows Thread Pool API, which provides a higher-level abstraction for managing threads and their execution.
Important: Ensure that the thread start routine (lpStartAddress) correctly handles synchronization and data sharing with other threads in the process to avoid race conditions and data corruption.

Requirements

Value
Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header
windows.h
Library
Kernel32.lib
DLL
Kernel32.dll

See Also