Microsoft Docs

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

NameTypeDescription
lpThreadAttributesLPSECURITY_ATTRIBUTESPointer to a SECURITY_ATTRIBUTES structure or NULL for default.
dwStackSizeSIZE_TInitial stack size, in bytes. 0 uses the default size.
lpStartAddressLPTHREAD_START_ROUTINEPointer to the application-defined function to be executed by the thread.
lpParameterLPVOIDSingle argument passed to the thread function.
dwCreationFlagsDWORDFlags that control the creation of the thread. Use 0 for immediate start or CREATE_SUSPENDED to start suspended.
lpThreadIdLPDWORDPointer 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

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;
}

Related Topics