C++线程安全共享数据需避免数据竞争,主要用std::mutex保护复合操作、std::atomic处理单变量读写、shared_ptr管理生命周期,并慎用全局/静态变量。

在C++中安全地进行线程间数据共享,核心是避免数据竞争(data race),即多个线程同时访问同一内存位置,且至少有一个是写操作,又无同步机制。关键手段是使用互斥量(std::mutex)、原子操作(std::atomic)或无锁编程技巧,配合恰当的生命周期管理。
适用于需要保护一段复杂逻辑(如读-改-写)的场景。注意:互斥量本身不能被拷贝,需通过引用或指针传递;锁的粒度要合理——太粗影响并发性,太细则易出错或死锁。
示例:两个线程对同一计数器做自增
#include <thread>
#include <mutex>
#include <iostream>
int counter = 0;
std::mutex mtx;
void increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx); // RAII 自动加锁/解锁
++counter;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join(); t2.join();
std::cout << "Final counter: " << counter << "\n"; // 输出 200000
}
适用于单个变量的读、写、自增等基础操作。原子类型提供无锁、线程安全的语义,性能通常优于互斥量,但不适用于复合操作(如“先读再条件更新”需 compare_exchange_weak)。
立即学习“C++免费学习笔记(深入)”;
示例:用 std::atomic_int 实现线程安全计数器
#include <thread>
#include <atomic>
#include <iostream>
std::atomic_int counter{0};
void increment_atomic() {
for (int i = 0; i < 100000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed);
}
}
int main() {
std::thread t1(increment_atomic);
std::thread t2(increment_atomic);
t1.join(); t2.join();
std::cout << "Final counter: " << counter.load() << "\n";
}
常见错误是在线程中访问局部变量地址,或提前释放堆内存。推荐方式包括:将数据作为对象成员、使用 std::shared_ptr 管理所有权、或明确约定生命周期由主线程负责。
std::shared_ptr<t></t> 保证其存活到所有线程结束std::jthread(C++20)自动 join,减少资源管理疏漏它们天然跨线程可见,但极易引发隐式共享和初始化顺序问题。C++11 起,带构造函数的静态局部变量是线程安全初始化的(一次且仅一次),但之后的访问仍需同步。
例如以下代码是安全的初始化,但后续修改仍需保护:
std::map<int, std::string>& get_cache() {
static std::map<int, std::string> cache; // 初始化线程安全
return cache;
}
// 使用时:
{
auto& c = get_cache();
std::lock_guard<std::mutex> lock(cache_mutex);
c[42] = "hello"; // 修改仍需加锁!
}
以上就是C++如何安全地进行线程间数据共享?(代码示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号