在 C++ 中使用多线程编程时,需要注意许多细节以避免潜在的问题。以下是一些关键点和注意事项:
1. 线程安全与数据竞争
- 数据竞争:当多个线程同时访问共享资源(如全局变量、堆内存等)且至少有一个线程在写入时,可能会导致未定义行为。
- 解决方法:
- 使用互斥锁(std::mutex)保护共享资源。
- 使用读写锁(std::shared_mutex)优化多线程读操作。
- 避免直接共享可变状态,尽量使用线程本地存储(thread_local)。
示例代码:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义互斥锁
int shared_data = 0;
void increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx); // 自动加锁和解锁
++shared_data;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
2. 死锁
- 定义:两个或多个线程互相等待对方释放资源,导致程序无法继续运行。
- 解决方法:
- 使用 std::lock 同时锁定多个互斥锁。
- 按固定顺序获取锁。
- 尽量减少锁的持有时间。
示例代码(防止死锁):
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx1, mtx2;
void task1() {
std::lock(mtx1, mtx2); // 同时锁定两个互斥锁
std::lock_guard<std::mutex> lock1(mtx1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(mtx2, std::adopt_lock);
std::cout << "Task 1" << std::endl;
}
void task2() {
std::lock(mtx2, mtx1); // 同时锁定两个互斥锁
std::lock_guard<std::mutex> lock1(mtx1, std::adopt_lock);
std::lock_guard<std::mutex> lock2(mtx2, std::adopt_lock);
std::cout << "Task 2" << std::endl;
}
int main() {
std::thread t1(task1);
std::thread t2(task2);
t1.join();
t2.join();
return 0;
}
3. 线程同步
- 条件变量:用于线程间的协调。
- 信号量:C++20 引入了标准库中的信号量(std::counting_semaphore 和 std::binary_semaphore)。
示例代码(使用条件变量):
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return ready; }); // 等待条件满足
std::cout << "Worker thread is processing data" << std::endl;
}
int main() {
std::thread t(worker);
{
std::lock_guard<std::mutex> lock(mtx);
ready = true; // 修改条件
}
cv.notify_one(); // 唤醒等待的线程
t.join();
return 0;
}
4. 线程生命周期管理
- 在主线程中需要确保子线程正确地启动和结束。
- 使用 join() 或 detach() 管理线程生命周期:
- join():阻塞主线程直到子线程完成。
- detach():让子线程独立运行,但需要注意资源管理。
示例代码:
#include <iostream>
#include <thread>
void task() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread t(task);
if (t.joinable()) {
t.join(); // 等待线程结束
}
std::cout << "Main thread ends" << std::endl;
return 0;
}
5. 异常处理
如果线程函数抛出异常,未被捕获的异常会导致程序终止。
确保在线程函数中捕获所有可能的异常。
示例代码:
#include <iostream>
#include <thread>
void task() {
try {
throw std::runtime_error("Error in thread");
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
}
int main() {
std::thread t(task);
t.join();
return 0;
}
6. 性能优化
- 避免过度加锁:频繁加锁会降低性能,可以使用无锁编程(如原子操作 std::atomic)。
- 任务划分:合理分配任务,避免线程饥饿或负载不均。
示例代码(使用原子操作):
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void increment() {
for (int i = 0; i < 100000; ++i) {
++counter; // 原子操作
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Counter: " << counter << std::endl;
return 0;
}
7. C++20 的新特性
- 协程:支持异步编程。
- latch 和 barrier:用于线程间同步。
- jthread:支持自动 join 的线程。
示例代码(使用 std::latch):
#include <iostream>
#include <thread>
#include <latch>
std::latch latch(2); // 初始化计数器为2
void task(int id) {
std::cout << "Task " << id << " completed" << std::endl;
latch.count_down(); // 减少计数器
}
int main() {
std::thread t1(task, 1);
std::thread t2(task, 2);
latch.wait(); // 等待计数器归零
t1.join();
t2.join();
std::cout << "All tasks completed" << std::endl;
return 0;
}
总结
C++ 多线程编程需要重点关注线程安全、同步机制、异常处理以及性能优化。通过合理使用标准库提供的工具(如 std::mutex、std::condition_variable、std::atomic 等),可以有效避免常见的多线程问题。