Threads and Locks
Why two threads corrupt shared data, and how mutexes, atomics and a fixed lock order keep it correct.
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.
| Java | C++17 | |
|---|---|---|
| Start | new Thread(task).start() | std::thread t(task); |
| Wait for it | t.join() | t.join() (required before t is destroyed) |
| Compile | plain javac | g++ -std=c++17 -pthread |
1 of 8