Chapter 01 · One line, three steps01 / 19

Two threads, one counter

A thread is one path of execution through a program. A program can run many threads at once, and they all share the same memory. That sharing makes threads fast and cheap to coordinate. It also makes them dangerous.

Here two threads, A and B, share one variable, count, which starts at 5. Each thread runs the same line of code once: count = count + 1.

Two increments, so count should end at 7. And it does. The timeline at the bottom records what ran, in order.

counter.cin the real world
int count = 5; // shared by every thread
 
void *worker(void *arg) {
count = count + 1;
return NULL;
}
 
pthread_create(&a, NULL, worker, NULL);
pthread_create(&b, NULL, worker, NULL);