Linux System Programming · beginner · ~8 min
Understand what a thread is and how it differs from a process.
A thread is a single flow of execution inside a process.
A process can run several threads at once. All the threads in a process share the same memory and the same open file descriptors. But each thread has its own stack.
On Linux and other POSIX systems, the standard threading library is pthreads.
A process is a running program. It has its own memory, its own file descriptors, and its own signal handlers.
A thread is a single execution context inside a process. A process can have many threads.
Threads in the same process:
malloc). If two threads write the same variable without coordinating, you get a race condition — two threads racing to touch the same data, with undefined behaviour as the result.On Linux and POSIX systems, the C threading API is pthreads (POSIX threads).
<pthread.h>.-pthread flag when you compile.#include <pthread.h>
#include <stdio.h>
static void *worker(void *arg) {
(void)arg;
printf("hello from a thread\n");
return NULL;
}
int main(void) {
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_join(t, NULL);
return 0;
}
/* compile with: gcc -pthread thread.c -o thread */
-pthread on the compile command. You will get a linker error such as undefined reference to pthread_create.<pthread.h>, and compile with -pthread.