Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see locking thread of std::mutex in Visual Studio?

Using Windows CRITICAL_SECTION, I can see the thread that locked it by expanding the variable:

enter image description here

However, I can't seem to do the same with std::mutex, and get a lot of useless values instead:

enter image description here

Is there a way around it that doesn't require modifying my code?

like image 227
riv Avatar asked Apr 30 '19 10:04

riv


People also ask

How does mutex know to lock?

Mutex only locks a thread. It does not lock a resource. You can still access it via direct memory manipulation. So in that sense it is not safe (but on the other hand nothing can stop you from direct memory manipulation).

What is locking in mutex?

Locks a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

Is mutex locked?

A Mutex is a lock that we set before using a shared resource and release after using it. When the lock is set, no other thread can access the locked region of code.

Can multiple threads lock on a mutex?

The non-member function lock allows to lock more than one mutex object simultaneously, avoiding the potential deadlocks that can happen when multiple threads lock/unlock individual mutex objects in different orders.


1 Answers

Thanks to @PeterT's comment, wrote a visualizer for various mutex types (place in /Documents/Visual Studio 2017/Visualizers/mutex.natvis):

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
  <Type Name="std::_Mutex_base">
    <Expand>
      <Item Name="[thread_id]">*(long*)((char*)&amp;_Mtx_storage+sizeof(_Mtx_storage)-8)</Item>
      <Item Name="[count]">*(int*)((char*)&amp;_Mtx_storage+sizeof(_Mtx_storage)-4)</Item>
    </Expand>    
  </Type>
  <Type Name="std::mutex">
    <DisplayString>mutex</DisplayString>
    <Expand>
      <ExpandedItem>(_Mutex_base*)this</ExpandedItem>
    </Expand>
  </Type>
  <Type Name="std::timed_mutex">
    <DisplayString>timed_mutex</DisplayString>
    <Expand>
      <Item Name="[locked]">_My_locked</Item>
    </Expand>
  </Type>
  <Type Name="std::recursive_mutex">
    <DisplayString>recursive_mutex</DisplayString>
    <Expand>
      <ExpandedItem>(_Mutex_base*)this</ExpandedItem>
    </Expand>
  </Type>
  <Type Name="std::recursive_timed_mutex">
    <DisplayString>recursive_timed_mutex</DisplayString>
    <Expand>
      <Item Name="[locked]">_My_locked</Item>
      <Item Name="[owner]">_My_owner</Item>
    </Expand>
  </Type>
</AutoVisualizer> 
like image 87
riv Avatar answered Oct 11 '22 01:10

riv