0
#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;
}

Here is my c++ code. As you can see, only one thread has the chance to execute at any time because of the mutex. In other words, most of threads are blocked by the mutex.

My question is if there is some tool or some technique to detect how many threads are blocked by mutex in an executable file without reading the source code?

Yves
  • 11,597
  • 17
  • 83
  • 180

1 Answers1

0

If it’s for debugging, use a debugger. On Windows, MSVC compiles std::mutex into either critical sections or SRW locks (depends on environment). Break execution of the app, and you’ll see how many threads are sleeping in EnterCriticalSection or AcquireSRWLockExclusive WinAPI.

If you want that info because you want to do something different in runtime based on that, I’m afraid std::mutex can’t do that. You should probably use some other synchronization primitives. I don’t know what it is you’re doing, but when I write complex multithreading stuff I often use conditional variables, and/or atomic operators i.e. Interlocked* on Windows, std::atomic in modern C++.

Soonts
  • 20,079
  • 9
  • 57
  • 130
  • Could you add some explanation on Linux? So should I use gdb on Linux to do so? – Yves Jul 29 '19 at 07:42
  • I have only used gdb a couple of times, but this answer https://stackoverflow.com/a/22980319/126995 should print you call stacks of all threads. Find out which kernel API std::mutex::lock compiles into (by looking in the STL headers, or by reading these stack traces in gdb), an search for that kernel call in the stacks. – Soonts Jul 29 '19 at 07:59