网站自动推广软件免费,公司网站备案怎么做,dz做电影网站,aspnet网站开发教程在 C 中#xff0c;互斥量#xff08;std::mutex#xff09;是一种用于多线程编程中保护共享资源的机制#xff0c;防止多个线程同时访问某个资源#xff0c;从而避免数据竞争#xff08;data race#xff09;和不一致的问题。 #x1f512; 一、基础用法#xff1a;s…在 C 中互斥量std::mutex是一种用于多线程编程中保护共享资源的机制防止多个线程同时访问某个资源从而避免数据竞争data race和不一致的问题。 一、基础用法std::mutex
头文件#include mutex
#include iostream
#include thread
#include mutexstd::mutex mtx; // 创建一个互斥量
int counter 0;void increment(int id) {for (int i 0; i 10000; i) {mtx.lock(); // 加锁counter; // 访问共享资源mtx.unlock(); // 解锁}
}你可以通过多个线程调用 increment()互斥量保证了线程安全。 ✅ 更推荐的方式使用 std::lock_guard
它是一种 RAII资源获取即初始化 的封装类作用域结束时会自动解锁非常安全防止漏解锁。
void increment(int id) {for (int i 0; i 10000; i) {std::lock_guardstd::mutex lock(mtx);counter;} // 作用域结束时自动释放锁
}⛔ 错误示例不要这样做
mtx.lock();
counter;
// 如果中间抛异常mutex 可能永远不会 unlock其他互斥量类型
类型说明std::mutex最基本的互斥量std::recursive_mutex支持同一线程多次加锁std::timed_mutex支持带超时的锁操作std::shared_mutexC17引入读写锁多个读一个写 示例多个线程安全地写输出
#include iostream
#include thread
#include mutexstd::mutex print_mtx;void safe_print(const std::string msg) {std::lock_guardstd::mutex lock(print_mtx);std::cout msg std::endl;
}int main() {std::thread t1(safe_print, hello from thread 1);std::thread t2(safe_print, hello from thread 2);t1.join();t2.join();return 0;
}⏳ try_lock() 与 timed_mutex
if (mtx.try_lock()) {// 成功获得锁mtx.unlock();
} else {// 没拿到锁干别的事
}std::timed_mutex tmtx;
if (tmtx.try_lock_for(std::chrono::milliseconds(100))) {// 拿到锁tmtx.unlock();
}总结
方法是否推荐用法说明mutex.lock()/unlock()❌ 不推荐容易忘记 unlockstd::lock_guard✅ 推荐简单安全std::unique_lock✅ 推荐需要更灵活控制时try_lock / timed_mutex✅ 用于尝试加锁或有时间要求 如你需要我帮你写一个完整的多线程例子比如生产者-消费者模型、线程池、文件读写等可以直接告诉我场景