c++ - 如果 mutex::lock() 已被另一个线程锁定,则多久检查一次解锁状态?

标签 c++ multithreading locking mutex stdthread

根据 cppreference , 用 std::mutex 参数构造一个 std::lock_guard 调用那个 mutexlock() 方法>.

根据 cplusplus , 关于 mutexlock() 方法:

If the mutex is locked by another thread, execution of the calling thread is blocked until unlocked by the other thread...

我不确定标题问题的措辞是否正确,所以我将其放在下面代码的上下文中。

我想对此进行测试,看看调用线程是否真的在等待解锁,而不是终止其可调用对象(例如函数、仿函数、lambda)的执行和/或抛出异常。以下代码有两个线程 t1t2,每个线程都使用指向相同函数 foo 的指针构造。每次调用 foo 都会 sleep_for 一定的时间,由 foounsigned 参数 决定num,在执行锁保护代码之前。受锁保护的代码本身包含另一个 sleep_for 周期,以使任何阻塞的执行周期更加明显:

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

std::mutex m;

void foo(unsigned num) {
    std::this_thread::sleep_for(std::chrono::milliseconds(num * 10));
    std::lock_guard<std::mutex> guard(m);
    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    std::cout << num << std::endl;
}

int main() {
    std::thread t1(foo, 10);
    std::thread t2(foo, 5);
    t1.join();
    t2.join();
}

控制台输出:

5
10

5 输出需要大约/至少 3.05 秒。 10 需要大约/至少额外 3 秒才能输出。这意味着 t2 首先执行 protected 代码,因为它在锁定 mutex 之前的等待时间较短。

我假设一旦从线程 t1 调用 foo 到达 lock_guard 行并找到 mutex 已经被t2 锁定,t1 不会终止执行或抛出异常。 t1 只是等待解锁。

std::mutex::lock()std::lock_guard 多久进行一次解锁检查?支票有多贵?检查是否像下面这样执行?

while (some_mutex.try_lock() == false) {
    std::this_thread::sleep_for(std::chrono::milliseconds(1))
}
// execute lock-protected code

最佳答案

How frequently does std::mutex::lock() or std::lock_guard make this check for the unlocking?

事实并非如此。它在操作系统内部阻塞,直到资源被释放。任何通过旋转实现这一点的操作系统都会引起投诉。

关于c++ - 如果 mutex::lock() 已被另一个线程锁定,则多久检查一次解锁状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034658/

相关文章:

c++ - 成员 func 如何以*编程方式*调用它的 'name of the object'?

在参数中强制执行单一类型的 C++ 参数包

c - 使用 pthreads 并行实现高斯消元

c - 在 C 中使用清理处理程序安全取消 pthread

C#,我可以在不尝试获取锁的情况下检查它吗?

c++ - Arduino 类层次结构、字符串和内存泄漏

c++ - opengl 3.1 纹理未加载

c++ - 条件变量通知后的执行顺序

perl - 如何在 Perl 中验证图像文件?

android - 在 synchronized(lock){lock.notify();} 中抛出 IllegalMonitorStateException ... 为什么?