使用std::mutex需包含头文件并定义互斥锁对象;2. 手动调用lock()/unlock()易因异常导致死锁,不推荐;3. 推荐使用std::lock_guard,利用RAII机制自动加解锁,确保异常安全;4. 多线程示例中,lock_guard保护共享计数器递增,避免数据竞争,最终结果正确。

在C++多线程编程中,std::mutex 是用于保护共享资源不被多个线程同时访问的核心工具。使用互斥锁可以避免数据竞争,保证线程安全。下面介绍其基本用法和常见模式。
1. 包含头文件并声明互斥锁
要使用互斥锁,需包含 头文件,并定义一个 std::mutex 对象:
#include #include #include std::mutex mtx; // 全局互斥锁int shared_data = 0;
2. 使用 lock() 和 unlock() 手动加锁解锁
最基础的方式是调用 lock() 加锁,操作完后调用 unlock() 解锁:
void unsafe_function() { mtx.lock(); // 加锁 shared_data++; // 安全访问共享数据 std::cout << "Data: " << shared_data << std::endl; mtx.unlock(); // 解锁}
注意:如果在 lock() 和 unlock() 之间发生异常或提前 return,unlock() 可能不会执行,导致死锁。因此不推荐直接使用这种方式。
立即学习“C++免费学习笔记(深入)”;
3. 使用 std::lock_guard 自动管理锁
更安全的做法是使用 std::lock_guard,它利用 RAII(资源获取即初始化)机制,在构造时加锁,析构时自动解锁:
void safe_function() { std::lock_guard guard(mtx); // 构造时自动 lock() shared_data++; std::cout << "Data: " << shared_data << std::endl; // 离开作用域时自动 unlock()}
即使函数中途抛出异常,lock_guard 的析构函数也会释放锁,确保不会死锁。
4. 在多线程中使用互斥锁示例
完整示例:创建多个线程对共享变量进行递增操作:
#include #include #include #include std::mutex mtx;int counter = 0;void increment(int n) { for (int i = 0; i < n; ++i) { std::lock_guard guard(mtx); counter++; }}int main() { std::vector threads; const int num_threads = 10; const int inc_per_thread = 1000; for (int i = 0; i < num_threads; ++i) { threads.emplace_back(increment, inc_per_thread); } for (auto& t : threads) { t.join(); } std::cout << "Final counter value: " << counter << std::endl; // 应为 10000 return 0;}
如果没有互斥锁,counter++ 可能出现竞态条件,结果小于预期。加上锁后,每次只有一个线程能修改 counter,保证了正确性。
基本上就这些。合理使用 mutex 配合 lock_guard,就能写出线程安全的 C++ 代码。关键是避免手动调用 lock/unlock,优先使用 RAII 封装。
以上就是c++++中的mutex互斥锁怎么用_c++多线程互斥锁使用方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482769.html
微信扫一扫
支付宝扫一扫