CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 5 of 6 · 2 min read

Ending

When the main thread ends

In plain words: How a program ends depends on which call ends it. Two small programs start a worker that sleeps one second and then prints worker done. They differ in how main ends.

If main simply returns, the C library calls exit, and exit ends the whole process, along with every thread in it:

main returns now

The worker never printed. If main instead calls pthread_exit(NULL), only the main thread ends, and the process lives until the last thread ends:

main exits with pthread_exit
worker done

This gives three rules:

What a thread does Effect
return from main, or exit() in any thread The whole process ends, all threads included
pthread_exit() in any thread Only that thread ends. The process ends when its last thread ends
return from a thread's start function The same as pthread_exit with that value

A crash in any thread ends the process too (page 1). The safe habit is simple: before main returns, join every thread that matters.

Read it as

The process lives as long as its last thread, unless somebody calls exit or a signal kills it. return from main is a call to exit.

Interview angle

Answer in your head first, then open it.

How do you create a thread in C?

Include pthread.h, call pthread_create with a start function and an argument, and compile with -pthread.

What does pthread_join do?

It waits for a thread to end and collects its return value.

What is a detached thread?

A thread that cleans up by itself and cannot be joined.

What happens if main returns while other threads run?

The process ends and the other threads are stopped.

How do the pthread functions report errors?

They return the error number and do not use errno.

Check yourself: 1. What ends the process: a return from main, or pthread_exit in main? 2. How does a thread return a result to its joiner? 3. What must you do before main returns if a worker is still needed?

Words you will meet

Word Meaning
POSIX threads (pthreads) The standard thread library for Unix-like systems
pthread_t The type that identifies a thread
Start function The function a new thread runs
Joinable Keeps its result until joined
Detached Cleans up by itself, cannot be joined
Error number The value pthread functions return on failure

Quick notes

  • pthread_create starts a new thread in the calling process that runs a given function with one argument, and stores the new thread's identifier.
  • A joinable thread keeps its exit status until another thread calls pthread_join for it.