你能在同一个块中的互斥锁 lock_guard 之前有代码吗

Can you have code before the mutex lock_guard within the same block

所以,这可能是一个显而易见的答案,但我只是有疑问,因为我没有看到它被使用过...

因此,使用正常的互斥量,您可以:

void func1()
{
    mymutex.lock();
    // do func1 stuff on shared data
    mymutex.unlock();
}

void func2()
{
    func1(); // also uses mymutex

    mymutex.lock();
    // do func2 stuff on shared data
    mymutex.unlock();
}

在哪里我们可以很容易地看到互斥部分的 start/end。

但是用 lock_guard 你能做同样的事情吗,即:

void func1()
{
    std::lock_guard<std::mutex> g(mymutex);
    // do func1 stuff on shared data
}

void func2()
{
    func1(); // also uses lock_guard on mymutex

    std::lock_guard<std::mutex> g(mymutex);
    // do func2 stuff on shared data
}

在这里,我怀疑你通常使用lock_guard来保护一个完整的c++块。但是在 func2 中,我首先调用 func1(它本身使用相同的互斥锁)然后我在 same 块中调用 lock_gaurd 但是 after调用 func1.

那是ok/safe要做的吗?还是 func2 中的 lock_guard 对 func1 有影响?

我最初以为没问题 - 但后来我的大脑开始告诉我这把锁很可疑。我可以很容易地在 func2 lock_guard 周围放置一个方块 - 但现在我需要知道它是否正常才能再次入睡 :o

很安全。请现在睡觉:)

当锁卫终止时(退出其范围时),解锁功能会自动为您执行

查看更多here

The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block.

When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.

The lock_guard class is non-copyable.