Why pthread Code Doesn't Run on Windows Natively - thesmartgirl/philo GitHub Wiki
You're correct โ code written using pthread
is not portable to Windows out of the box. Here's why, and what your options are:
-
Windows doesn't support POSIX Threads (pthreads) in its standard libraries.
-
The Windows API for threads (
CreateThread
,WaitForSingleObject
, etc.) is completely different from thepthread_*
family. -
Windows uses its own models for mutexes, TLS, condition variables, etc.
So a pthread
program won't compile or run on Windows unless you take extra steps.
-
Cygwin provides a full POSIX environment on Windows, including
pthread.h
. -
MinGW-w64 includes a lightweight POSIX thread implementation (
pthreads-win32
). -
You can compile pthread-based code on Windows using:
gcc -pthread mycode.c -o myprogram.exe
โ Pros:
-
Minimal changes to your existing code.
-
Still uses
pthread_create
, etc.
โ Cons:
-
Adds a dependency layer.
-
Not true native Windows performance.
-
C11
threads.h
: Standardized in C11, some compilers support it (thrd_create
, etc.). -
C++11
std::thread
: Native and portable, works on Linux, Windows, macOS. -
Boost.Thread: Full-featured, cross-platform thread abstraction in C++.
โ Best choice for portable code going forward.
You can write a wrapper layer like this:
#ifdef _WIN32
#include <windows.h>
typedef HANDLE thread_t;
#define THREAD_FUNC_RETURN DWORD WINAPI
#else
#include <pthread.h>
typedef pthread_t thread_t;
#define THREAD_FUNC_RETURN void *
#endif
Then in your code:
THREAD_FUNC_RETURN my_thread(void *arg) {
// shared logic
}
โ This allows you to write thread-agnostic code by wrapping platform-specific APIs.
Question | Answer |
---|---|
Can I run pthread code on Windows? | โ Not natively. |
Any way to make it work? | โ Use MinGW/Cygwin or rewrite with native WinAPI |
What's best for portability? | โ Use C++ std::thread or abstract APIs |
If you'd like, I can help you rewrite a pthread example into portable std::thread
C++ or show how to set up pthreads on Windows using MinGW.