C++ 线程安全备忘(Thread Safety Cheat Sheet)
中文 | English |
一、线程安全的概念 | 1. Concept of Thread Safety |
线程安全指在多线程环境中,多个线程访问同一资源时,不会导致竞态条件、数据破坏或未定义行为。 | Thread safety means that in a multithreaded environment, multiple threads accessing the same resource will not cause race conditions, data corruption, or undefined behavior. |
简单说,就是保证程序正确性和稳定性,即使多线程同时执行相关代码。 | In short, it guarantees program correctness and stability even when multiple threads execute related code simultaneously. |
二、线程安全的级别 | 2. Levels of Thread Safety |
不安全(Not thread-safe):多线程同时访问会导致错误或竞态。 | Not thread-safe: concurrent access by multiple threads can cause errors or race conditions. |
线程安全(Thread-safe):多线程访问不会产生竞态,行为正确。 | Thread-safe: multiple threads can access safely without race conditions and behave correctly. |
可重入(Reentrant):函数可被多线程/中断安全调用,不依赖共享状态。 | Reentrant: functions can be safely called by multiple threads or interrupts, without relying on shared state. |
线程局部(Thread-local):每个线程拥有独立变量副本,互不干扰。 | Thread-local: each thread has its own copy of variables, avoiding interference. |
三、C++中实现线程安全的常用方法 | 3. Common Ways to Achieve Thread Safety in C++ |
1. 互斥锁(Mutex):用std::mutex加锁,保证同一时刻只有一个线程访问共享资源。 | 1. Mutex: use std::mutex to lock and ensure only one thread accesses shared resource at a time. |
示例: | Example: |
```cpp | ```cpp |
std::mutex mtx; | std::mutex mtx; |
int shared_data = 0; | int shared_data = 0; |
void safe_increment() { | void safe_increment() { |