繁体   English   中英

为什么lock_guard可以通过unique_lock获得已经锁定的互斥锁?

[英]why lock_guard can get an already locked mutex by unique_lock?

我读使用的示例代码condition_variable 这里 我发布以下代码:

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
    // Wait until main() sends data
    std::cout << "------------------------\n";
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{return ready;});

    // after the wait, we own the lock.
    std::cout << "Worker thread is processing data\n";
    data += " after processing";

    // Send data back to main()
    processed = true;
    std::cout << "Worker thread signals data processing completed\n";

    // Manual unlocking is done before notifying, to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lk.unlock();
    cv.notify_one();
}

int main()
{
    std::thread worker(worker_thread);

    data = "Example data";
    // send data to the worker thread
    {
        std::lock_guard<std::mutex> lk(m);
        ready = true;
        std::cout << "main() signals data ready for processing\n";
    }
    cv.notify_one();

    // wait for the worker
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return processed;});
    }
    std::cout << "Back in main(), data = " << data << '\n';

    worker.join();

    return 0;
}

我的问题是worker_thread首先启动,因此我假设互斥锁mworker_thread锁定了,但是为什么在main互斥锁m仍然可以被lock_guard锁定?

条件变量只是三脚架的一部分。

这三个部分是条件变量,状态和保护状态的互斥量。

条件变量提供了一种在状态更改时发出通知的机制。

此操作使用所有3:

cv.wait(lk, []{return ready;})

条件变量的方法需要一个锁(必须已获取)和一个lambda(用于测试状态)。

wait方法中, lk解锁,直到条件变量检测到消息(可能是虚假的)为止。 当检测到消息时,它将重新锁定互斥锁并运行测试(其目的是确定检测是否虚假的)。 如果测试失败,它将解锁并再次等待:如果测试通过,它将保持锁定并退出。

还有一个“测试抛出”路径,根据您所实现的代码的标准版本(C ++ 11有一个缺陷,IIRC),它会导致不同的锁定状态。

您错过的重要一件事是, wait解锁传入的互斥量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM