如何检测线程是否由于互斥而被阻止

时间:2019-07-29 07:05:20

标签: multithreading mutex

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

std::mutex mtx;
int i = 0;    

void func()
{
    std::lock_guard<std::mutex> lock(mtx);
    std::cout<<++i<<std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(8000));
}

int main() {
    std::thread t1(func);
    std::thread t2(func);
    std::thread t3(func);
    std::thread t4(func);
    t1.join();
    t2.join();
    t3.join();
    t4.join();

    return 0;
}

这是我的c ++代码。如您所见,由于互斥,只有一个线程可以在任何时间执行。换句话说,大多数线程都被互斥锁阻塞。

我的问题是,是否有某种工具或某种技术可以在不读取源代码的情况下检测到可执行文件中的互斥锁阻止了多少个线程?

1 个答案:

答案 0 :(得分:0)

如果用于调试,请使用调试器。在Windows上,MSVC将std :: mutex编译为关键部分或SRW锁(取决于环境)。中断应用程序的执行,您将看到EnterCriticalSection或AcquireSRWLockExclusive WinAPI中有多少个线程在休眠。

如果您想要该信息是因为您希望基于此在运行时做一些不同的事情,恐怕std :: mutex无法做到这一点。您可能应该使用其他一些同步原语。我不知道你在做什么,但是当我写复杂的多线程东西时,我经常使用条件变量和/或原子运算符,即Windows上的Interlocked *,现代C ++中的std :: atomic。

相关问题