Linux System Programming · beginner · ~8 min

What are threads? Why use them in C?

Understand what a thread is and how it differs from a process.

Overview

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.

Lesson

Processes vs. threads

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:

  • Share the same memory and the same file descriptors.
  • Each keep their own stack and register state.

Why use threads

  • Parallelism — on a multi-core CPU, several threads can run computations at the same time.
  • Overlap — one thread can wait on a slow read while another keeps the program responsive.
  • Shared state — threads talk through shared memory, which is faster than communicating between separate processes.

Why threads are risky

  • All threads in a process see the same heap memory (the memory you get from 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.
  • Cleanup mistakes are costly. A crash in one thread can bring down the entire program.

The pthreads API

On Linux and POSIX systems, the C threading API is pthreads (POSIX threads).

  • Include the header <pthread.h>.
  • Link with the -pthread flag when you compile.

Code examples

#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 */

Common mistakes

  • Forgetting -pthread on the compile command. You will get a linker error such as undefined reference to pthread_create.
  • Treating threads like processes. Threads share memory. Changing shared state without a mutex (a lock that lets only one thread touch the data at a time) is a bug.

Summary

  • A thread is one flow of execution inside a process.
  • Threads in a process share memory and file descriptors, but each has its own stack.
  • Use the pthreads API via <pthread.h>, and compile with -pthread.
  • Shared memory is powerful but causes race conditions if threads write the same data without coordination.

Practice with these exercises