Create Threads with CreateThread and _beginthreadex
Compare CreateThread and _beginthreadex on Windows, see why C runtime code should use the second, and pass arguments, return values and handles safely.

Windows gives a C programmer two ways to start a thread, and they look interchangeable. CreateThread is the Win32 call, from kernel32. _beginthreadex is the C runtime's wrapper around it, from <process.h>. Both return a handle, both take a start routine and an argument, and both appear in plausible-looking tutorials. The difference is not cosmetic, and the documentation steers programs that use the C library toward the second. This post shows both, explains what the runtime wrapper does that the bare call does not, and covers the parts that cause real bugs in either: passing arguments whose lifetime ends too soon, getting a result back, and closing the handle.
The examples use the Windows 11 SDK (10.0.26100) with MSVC 19.4 on x64 and the Universal C Runtime. The functions are documented on Microsoft Learn under CreateThread and _beginthread, _beginthreadex.
CreateThread
#include <windows.h>
#include <stdio.h>
static DWORD WINAPI worker(LPVOID arg)
{
int n = *(int *)arg;
DWORD sum = 0;
for (int i = 1; i <= n; i++)
sum += (DWORD)i;
return sum;
}
int wmain(void)
{
int limit = 100;
DWORD tid = 0;
HANDLE th = CreateThread(NULL, 0, worker, &limit, 0, &tid);
if (th == NULL) {
fwprintf(stderr, L"CreateThread failed: %lu\n", GetLastError());
return 1;
}
WaitForSingleObject(th, INFINITE);
DWORD result = 0;
GetExitCodeThread(th, &result);
wprintf(L"sum 1..%d = %lu\n", limit, result);
CloseHandle(th);
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE create.c
create.execreate.c
sum 1..100 = 5050The parameters are: security attributes (NULL for the default), initial stack size (0 for the executable's default, normally 1 MiB reserved), the start routine, one pointer argument, creation flags, and an optional pointer that receives the thread id. The start routine must be declared exactly DWORD WINAPI f(LPVOID). On 32-bit x86 the WINAPI convention is __stdcall, and a mismatch corrupts the stack, so write it even though x64 ignores it.
The return value of the routine is the thread's exit code. GetExitCodeThread reads it once the thread has finished, which is the simple way to get one 32-bit result back. For anything bigger, pass a pointer to a structure and let the thread fill it, as shown below.
Passing CREATE_SUSPENDED in the flags creates the thread without running it, so that you can set its priority, assign it to a job or set an affinity before calling ResumeThread.
What the C runtime needs from a thread
The C runtime keeps per-thread state: the value of errno, the internal buffer used by strtok, the locale in effect, the seed of rand in some implementations, and the state of the _set_invalid_parameter_handler mechanism. In the older static runtimes, this state was allocated lazily or by the thread-start wrapper. A thread created with plain CreateThread that then called into the runtime could find no per-thread block, and the runtime would allocate one on first use, with no one to free it on exit. That produced a small leak per thread, and in a low-memory moment a failure to allocate the block that the runtime treated as fatal.
_beginthreadex solves it by wrapping the start routine. It allocates the runtime's per-thread data, calls CreateThread with an internal start function, and that function initializes the runtime state, calls your routine and, when it returns, releases the state before the thread ends. The documentation states the rule directly: a thread in an executable that calls the C run-time library should use _beginthreadex and _endthreadex, and a thread created with CreateThread that calls the runtime can lead to the runtime terminating the process under low memory.
With the Universal C Runtime that ships with Windows 10 and later, the per-thread state is allocated and freed more robustly than it once was, and the practical danger has shrunk. The documented guidance has not changed, and a program that calls any runtime function from a thread should follow it.
_beginthreadex
#include <windows.h>
#include <errno.h>
#include <process.h>
#include <stdio.h>
struct job {
int n; /* input */
unsigned result; /* output, written by the thread */
};
static unsigned __stdcall worker(void *arg)
{
struct job *j = arg;
unsigned sum = 0;
for (int i = 1; i <= j->n; i++)
sum += (unsigned)i;
j->result = sum;
printf("worker: computed %u\n", sum); /* CRT call, safe here */
return 0;
}
int wmain(void)
{
struct job job = { 100, 0 };
unsigned tid = 0;
uintptr_t h = _beginthreadex(NULL, 0, worker, &job, 0, &tid);
if (h == 0) {
fwprintf(stderr, L"_beginthreadex failed, errno=%d\n", errno);
return 1;
}
HANDLE th = (HANDLE)h;
WaitForSingleObject(th, INFINITE);
wprintf(L"main: result = %u\n", job.result);
CloseHandle(th);
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE beginex.c
beginex.exebeginex.c
worker: computed 5050
main: result = 5050The signature differs from CreateThread in ways that matter. The start routine returns unsigned and is declared __stdcall, not DWORD WINAPI. The function returns a uintptr_t, so the code casts it to HANDLE, and a zero return, not NULL through the usual handle check, signals failure, with errno and _doserrno set instead of GetLastError. And the thread id is returned through an unsigned *.
The runtime also provides _endthreadex(code) to end the thread from inside a routine, which is called automatically when the routine returns, so you rarely write it. Calling ExitThread instead on a runtime-using thread skips the cleanup and brings back the leak that _beginthreadex was meant to prevent.
One more useful property: the handle from _beginthreadex must be closed with CloseHandle by the caller, unlike the sibling _beginthread, which closes it automatically at thread exit and thereby makes it impossible to wait on the thread safely. Avoid _beginthread.
The argument must outlive the call
Both functions return as soon as the thread is created, and the new thread starts at some later moment. The argument pointer is read by the new thread, so whatever it points to must still exist then. The classic bug passes the address of a loop variable:
for (int i = 0; i < 4; i++)
th[i] = CreateThread(NULL, 0, worker, &i, 0, NULL); /* wrong */By the time any thread reads *arg, the loop has moved on, and several threads see the same value, or the value after the loop ended. A correct version gives each thread its own storage:
static int ids[4];
for (int i = 0; i < 4; i++) {
ids[i] = i;
th[i] = CreateThread(NULL, 0, worker, &ids[i], 0, NULL);
}When the data is created per thread, allocate it on the heap, let the thread free it, and never use stack memory that the creating function might return from. For many arguments, put them in a structure as in the example above.
Getting results back
There are three reliable ways. The exit code, as in the first program, carries one 32-bit value. A structure that the creating code owns and the thread fills carries anything, with WaitForSingleObject on the thread handle as the synchronization: when the wait returns, the thread has finished and its writes are visible. And an event or a queue carries results while the thread keeps running.
The wait on the thread handle works because a thread object becomes signaled when the thread ends. That is also the answer to "how do I know it is done". It is not a pointer-sized flag you test in a loop, which would waste a processor and might not see the update without a barrier.
Waiting for several threads
#include <windows.h>
#include <process.h>
#include <stdio.h>
#define N 4
static unsigned __stdcall work(void *arg)
{
unsigned id = (unsigned)(uintptr_t)arg;
Sleep(50 * (id + 1)); /* pretend to work */
return id * 10; /* exit code */
}
int wmain(void)
{
HANDLE th[N];
for (unsigned i = 0; i < N; i++) {
th[i] = (HANDLE)_beginthreadex(NULL, 0, work, (void *)(uintptr_t)i, 0, NULL);
if (th[i] == 0)
return 1;
}
WaitForMultipleObjects(N, th, TRUE, INFINITE);
for (unsigned i = 0; i < N; i++) {
DWORD code;
GetExitCodeThread(th[i], &code);
wprintf(L"thread %u exited with %lu\n", i, code);
CloseHandle(th[i]);
}
return 0;
}thread 0 exited with 0
thread 1 exited with 10
thread 2 exited with 20
thread 3 exited with 30Passing the index by value, cast through uintptr_t, avoids the lifetime problem entirely for a small integer. WaitForMultipleObjects with TRUE blocks until all four threads have ended, and it can wait on at most 64 handles at a time. For more threads, a thread pool or a counting scheme with an event is needed.
Per-thread data and shared data
Anything that two threads touch needs protection, as in any threaded language. A thread-local variable in Win32 C is declared with __declspec(thread), giving each thread its own copy:
static __declspec(thread) int depth;This is faster than the older TlsAlloc family of functions, which are still used for dynamically many slots and for DLLs loaded at run time on older systems. Shared counters use the interlocked functions, and shared structures use a CRITICAL_SECTION or an SRWLOCK, which the other posts on synchronization cover.
Stack size and limits
Each thread reserves address space for its stack: 1 MiB by default for most executables, set at link time with /STACK:reserve,commit. The memory is reserved up front and committed as the stack grows. A recursion that goes too deep ends with a stack overflow exception. A program that starts thousands of threads can run out of address space on 32-bit builds and runs into scheduler overhead on any build, because the cost of a thread is far more than its stack. The second argument to CreateThread and _beginthreadex, dwStackSize, overrides the size for one thread, and the flag STACK_SIZE_PARAM_IS_A_RESERVATION makes it a reservation limit instead of the committed size.
Choosing between them, and a third option
For a C or C++ program that links the C runtime, which is nearly every program, use _beginthreadex. Use CreateThread when you are writing code with no runtime dependency, such as a freestanding program that links only kernel32, or when the thread calls only Win32 functions and the routine is in a DLL built without the runtime.
For short tasks, creating a thread each time is wasteful. The Windows thread pool API runs work items on pooled threads: CreateThreadpoolWork, SubmitThreadpoolWork and WaitForThreadpoolWorkCallbacks give you parallelism without managing threads at all. Reach for it when you have many small units of work.
C11 threads, thrd_create from <threads.h>, are supported by recent MSVC versions and wrap the same machinery, which is useful for code that also builds on Linux.
Mistakes to watch for
Calling runtime functions from a
CreateThreadthread in a program with the static runtime.Passing the address of a local variable that goes out of scope.
Forgetting
CloseHandle, leaking one handle per thread.Checking
_beginthreadexfailure withGetLastError: it returns 0 and setserrnoinstead.Using
_beginthreadand then waiting on its handle, which may already be closed.Starting a thread from
DllMainand waiting for it, which deadlocks on the loader lock.


