Thread safety¶
Category: Safety in languages · Status: stub · Lessons: chapter 02, Shared state
One line: Code or data is thread-safe if it behaves correctly when used from several threads at once, without its callers adding any synchronization.
Also called: thread-safe, MT-safe.
How it connects¶
- See also: Concurrent data structures, Reentrancy
In each language¶
| Rust | Checked by the compiler through Send ↗ and Sync ↗: a type is Sync if and only if &T is Send |
| Go | Documented type by type: sync.Map ↗ is safe for concurrent use without extra locking, built-in maps are not ↗ |
| C++ | Containers ↗: different containers may be used from different threads, and const member functions on the same container concurrently |
| Java | ArrayList ↗ is not synchronized and suggests wrapping it with Collections.synchronizedList at creation |
| Python | Thread Safety Guarantees ↗ grades built-in types from incompatible through safe on shared objects to atomic |
| C# | The System.Collections.Concurrent ↗ collections are thread-safe and scalable |
| Swift | Sendable ↗: a thread-safe type whose values can be shared across concurrent contexts without risk of data races |
| The operating system | POSIX §2.9.1 ↗: every function is thread-safe except a listed set, such as strtok and asctime |
Where to read more¶
- In a sibling library: Python: The format mini-language — a formatting call that changes process-wide state ↗
- In the books: Java Concurrency in Practice, Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea — ch. 2, 'Thread Safety'
- In the books: Pro Asynchronous Programming with .NET, Richard Blewett, Andrew Clymer — ch. 4, 'Basic Thread Safety'
- In the books: Rust Atomics and Locks, Mara Bos — ch. 1, 'Basics of Rust Concurrency' → 'Thread Safety: Send and Sync'
- In the books: Programming with POSIX Threads, David R. Butenhof — ch. 6, 'POSIX Adjusts to Threads' → 'Thread-safe functions'
- In the books: Concurrency with Modern C++, Rainer Grimm — ch. 5, 'Case Studies' → 'Thread-Safe Initialisation of a Singleton'
- In the books: The Art of Concurrency, Clay Breshears — ch. 4, 'Eight Simple Rules for Designing Multithreaded Applications' → 'Rule 4: Make Use of Thread-Safe Libraries Wherever Possible'
- Notes: threads - general - thread safety ↗
- Reference: Wikipedia: Thread safety ↗