Part 6 of 7 · 3 min read
Rules
Rules for writing threaded code
The safest threaded code shares as little as possible. These rules follow from the pages above:
- Prefer private data. Locals, arguments and
__threadvariables belong to one thread and need no lock. - Share only what must be shared, and keep the shared data in as few places as possible.
- Give each thread its own work and result slot, as in the parallel sum of page 2. The main thread combines the answers after
pthread_join. - Lock every access to shared data that anyone changes, reads included, with the same lock.
- Hold locks briefly. Do no slow calls such as reading a file while holding one.
- Use the
_rfunctions, and check the manual's note on thread safety. - Never return or pass the address of a thread's local variable to a thread that might use it after the first thread ends.
Read it as
A race exists when two threads touch the same data, at least one writes, and nothing orders them. Remove any one of the three and the race is gone: do not share, do not write, or add a lock.
Interview angle
Answer in your head first, then open it.
What is a race condition?
A result that depends on thread timing, when threads access the same data without coordination and at least one writes.
Why is counter++ not atomic?
It is a load, an add and a store, so another thread can run in between.
What makes a function thread-safe?
It keeps no unprotected shared state; strtok_r is safe, strtok is not.
What is thread-local storage?
Variables with one copy per thread, such as errno.
How do you remove a race?
Avoid sharing, avoid writing, or protect the access with a lock.
Check yourself:
1. Name the three conditions that together make a race.
2. Why should a thread hold a lock for as short a time as possible?
3. Why combine results after pthread_join instead of during the work?
Words you will meet
| Word | Meaning |
|---|---|
| Race condition | A result that depends on thread timing |
| Mutex | A lock that one thread at a time can hold |
| Critical section | Code run while holding the lock |
| Thread-safe | Correct when called by several threads at once |
| Reentrant | Uses only its own arguments and locals |
| Thread-local storage | A separate copy of a variable for each thread |
Quick notes
- A race condition is a flaw in which the result of a program depends on the relative timing of its threads or processes, usually because two of them access the.
- A mutex is a lock that at most one thread can hold at a time; a thread that tries to take a held mutex waits until it is released.
- A thread-safe function is a function that gives correct results when several threads call it at the same time, because it keeps no unprotected shared state, or protects the state it keeps with a lock.
- Thread-local storage is memory that is private to one thread: a variable declared with
__threadhas a separate instance for each thread, and a thread can read and write only its own.