/
How to launch a thread in Windows versus POSIX

How to launch a thread in Windows versus POSIX

This is the simplest code I can think of to show launching a thread in windows - you can use the C sandbox.

#include <stdio.h> #include <windows.h> DWORD ThreadProc(void* pObject){ printf("Hello thread %li\n", (long)pObject); return 0; } int main(){ DWORD ThreadId; HANDLE ThreadHandle = CreateThread(NULL,0,&ThreadProc,(void*)111, 0, &ThreadId); printf("Hello world of C!\n"); Sleep(1); return 0; }

Without the sleep call the program can exit before we have a change to run the thread. This is what we see when we run it:

C:\Users\eliotmuir\scratch\core\sandbox_c>test Hello world of C! Hello thread 111

This is what the same code looks like with pthreads (the name of the POSIX threads):

#include <stdio.h> #include <pthread.h> void* ThreadProc(void* pObject){ printf("Hello thread %li\n", (long)pObject); return 0; } int main(){ printf("Hello world of C!\n"); pthread_t Thread; int Result = pthread_create(&Thread, NULL, &ThreadProc, (void*)111); pthread_detach(Thread); return 0; }

With POSIX threads one would need to call pthread_join to clean up thread thread when it is done if we didn’t call pthread_detach. I think this is really what I would see as unnecessary flexibility in the pthread library - at least based on my experience of how the applications I have architected end up using threads.

 

Related content

What are threads?
What are threads?
More like this
Windows is slow to start processes
Windows is slow to start processes
More like this
If a process hangs how do we get the output with popen
If a process hangs how do we get the output with popen
More like this
Mutex
More like this
Global Interpreter Lock - GIL
Global Interpreter Lock - GIL
More like this
Blocking calls in an event loop thread
Blocking calls in an event loop thread
More like this