std::mutex和std::lock_guard用于C++线程同步,前者提供加锁解锁功能,后者通过RAII机制自动管理锁,防止数据竞争。

在C++多线程编程中,std::mutex 和 std::lock_guard 是实现线程同步的基本工具。它们用于保护共享数据,防止多个线程同时访问导致数据竞争和未定义行为。
std::mutex 是一个同步原语,用来确保同一时间只有一个线程可以进入临界区(即访问共享资源的代码段)。
常用成员函数:
直接使用 lock/unlock 容易出错,比如忘记 unlock 或异常导致提前退出。因此推荐配合 RAII 机制使用。
立即学习“C++免费学习笔记(深入)”;
std::lock_guard 是一个RAII风格的锁管理类。它在构造时自动加锁,析构时自动解锁,确保即使发生异常也能正确释放锁。
使用步骤:
下面是一个使用 std::mutex 和 std::lock_guard 保护共享账户余额的完整例子:
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
class BankAccount {
private:
double balance;
std::mutex mtx; // 互斥锁
public:
BankAccount(double initial) : balance(initial) {}
void deposit(double amount) {
std::lock_guard<std::mutex> lock(mtx); // 自动加锁
balance += amount;
std::cout << "Deposited " << amount
<< ", new balance: " << balance << std::endl;
}
void withdraw(double amount) {
std::lock_guard<std::mutex> lock(mtx);
if (balance >= amount) {
balance -= amount;
std::cout << "Withdrew " << amount
<< ", new balance: " << balance << std::endl;
} else {
std::cout << "Failed to withdraw " << amount
<< ", insufficient funds" << std::endl;
}
}
double get_balance() const {
std::lock_guard<std::mutex> lock(mtx);
return balance;
}
};
void worker(BankAccount& account) {
for (int i = 0; i < 5; ++i) {
account.deposit(100);
account.withdraw(50);
}
}
int main() {
BankAccount account(1000);
std::vector<std::thread> threads;
// 创建 3 个线程同时操作账户
for (int i = 0; i < 3; ++i) {
threads.emplace_back(worker, std::ref(account));
}
for (auto& t : threads) {
t.join();
}
std::cout << "Final balance: " << account.get_balance() << std::endl;
return 0;
}
输出示例(顺序可能不同):
Deposited 100, new balance: 1100由于每个操作都被 std::lock_guard 保护,不会出现余额计算错误或打印混乱的情况。
使用互斥锁时要注意以下几点:
基本上就这些。std::mutex 配合 std::lock_guard 提供了简单可靠的线程安全机制,是C++多线程编程的基石之一。
以上就是c++++ std::mutex和std::lock_guard怎么用_c++互斥锁机制与线程同步实例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号