Is it possible to get the return value of a function started with the CreateThread function or is the only way I can get a value from it to use global variables? I searched but i found nothing.
Thanks.
Is it possible to get the return value of a function started with the CreateThread function or is the only way I can get a value from it to use global variables? I searched but i found nothing.
Thanks.
Short answer for : yes — you can get a thread function’s return value (its exit code). and pointed you in the right direction. A few practical notes, pitfalls and alternatives that are missing from the replies will make the approach safe and usable in real code.
A typical pattern is: create the thread, wait for it to finish, call GetExitCodeThread to read the DWORD exit code, then close the handle. Don’t call GetExitCodeThread expecting a meaningful value while the thread is still running — it will usually return STILL_ACTIVE. Also remember the exit value is a 32-bit DWORD, so don’t try to return pointers or 64-bit values through the exit code on x64 systems; pass pointers via the thread parameter or use synchronized shared storage instead.
Example (Win32-style):
DWORD WINAPI Worker(LPVOID param) {
// do work
return 123; // must fit in DWORD
}
HANDLE h = CreateThread(NULL, 0, Worker, arg, 0, NULL);
WaitForSingleObject(h, INFINITE);
DWORD exitCode = 0;
GetExitCodeThread(h, &exitCode);
CloseHandle(h); If your thread uses C runtime functions, prefer the CRT-safe thread start (_beginthreadex) to avoid CRT cleanup problems. For modern C++ code, prefer std::thread / std::async / std::future (or std::promise) — they give direct, type-safe return values and avoid Win32 handle/exit-code hassles:
auto fut = std::async(std::launch::async, [](){ return computeValue(); });
auto result = fut.get(); Bottom line: avoid globals. Use the thread exit code for simple 32-bit results (with WaitForSingleObject), use _beginthreadex when the CRT is involved, and prefer std::future/std::async or promise/future for rich, type-safe returns.
Jump to Post— nucleon 114Try GetExitCodeThread.
Is it possible to get the return value of a function started with the CreateThread function or is the only way I can get a value from it to use global variables? I searched but i found nothing.
Thanks.
Thanks for the quick answers :D
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.