teacher
Sign in

Threads and Locks

Why two threads corrupt shared data, and how mutexes, atomics and a fixed lock order keep it correct.

28 min5 interactive3 problems

Threads in one minute

A process is a running program with its own memory. A thread is one path of execution inside it. All threads of a process share the same memory.

Why use them:

  • Use several CPU cores at once.
  • Keep working while another thread waits for the network or disk.

Sharing memory is the problem. As soon as two threads touch the same variable and at least one writes, you need a rule for who goes first.

JavaC++17
Startnew Thread(task).start()std::thread t(task);
Wait for itt.join()t.join() (required before t is destroyed)
Compileplain javacg++ -std=c++17 -pthread
1 of 8