Threads & Concurrency

pthreads and standard threads

/ pthreads -> 'PEE-threads'; POSIX -> 'PAH-ziks' /

Once you understand what a thread is, you need a concrete way to ask for one. On Unix-like systems the classic way is pthreads - POSIX threads, a standard library of functions that create and manage threads. The two you meet first are pthread_create(), which starts a new thread running a function you name, and pthread_join(), which waits for that thread to finish before you continue. With just those two you can spawn a worker and later collect its result.

Here is the shape of it in plain steps. You write a function the new thread will run, with a fixed signature: it takes one void * argument (so you can pass it any data via a pointer) and returns a void * (so it can hand a result back). You call pthread_create(), passing it a pointer to a pthread_t variable (which it fills in as a handle to the new thread), the function to run, and the argument to pass. The new thread begins running that function immediately, in parallel with your code. Later you call pthread_join() on the handle; it blocks until that thread returns, and gives you back the thread's return value. C added its own portable version in C11 (the threads.h header, with thrd_create() and thrd_join()), and C++11 added std::thread, but on Linux and macOS these are commonly built on top of pthreads underneath.

Why this matters: pthreads is the lingua franca of threading in C on Unix. The names are clunky and the error handling is manual (most functions return 0 on success and an error number otherwise), but the model is small and clear: create, run a function, join. Everything harder in this field - locking, signalling, atomics - is built on top of this basic ability to create threads that share memory. Get comfortable with create-and-join first; the hazards come from what those threads do once they are running.

A minimal create-and-join, ignoring error checks for clarity: pthread_t t; pthread_create(&t, NULL, worker, arg); ... pthread_join(t, NULL); where worker has the signature void *worker(void *arg). Compile with gcc main.c -pthread.

Create a thread to run worker(), do other work, then join to wait for it to finish.

You must link with -pthread (not just include the header), or the program may compile yet behave wrongly. And pthread functions return an error number directly - they do not set errno - so checking the return value, not errno, is how you detect failure.

Also called
POSIX threadsC11 threadsstd::threadPOSIX 執行緒