YC Yc.W home Systems · C++ · AI Infrastructure
C & C++ · Note

C++ mutex (待验证)

Explore all C & C++ notes →

在使用 std::mutex 时,并不要求声明为全局变量或静态成员;它也可以是类的普通非静态数据成员,选择取决于需要共享的范围和生命周期。

#include <mutex>

<!--more-->

class A {
public:
  void f();
  void f2();
private:
  std::mutex m_Mutex;
};

void A::f()
{
  std::lock_guard<std::mutex> guard(m_Mutex);
  // 访问共享数据
}

void A::f2()
{
  std::lock_guard<std::mutex> guard(m_Mutex);
  // 访问共享数据
}

std::mutex 不可复制或移动,并且不能在其仍被某个线程持有时销毁;使用 std::lock_guard 等 RAII 包装器可以在作用域结束时自动解锁。

参考:cppreference:std::mutex 和 非静态成员函数。


AI 修改声明: 本文由 LLM 协助校对,最近修改时间:2026-09-25 02:02(UTC+08:00)。


← Previous Static Analyzers-C++