8

I find that the std::mutex implementation in Visual Studio 2013 is too slow. It uses a heavy weight mutex to assure that synchronization can be achieved even between processes which is all fine and dandy; Unless you're not talking to other processes and could really use that extra speed that CRITICAL_SECTION with it's spin-lock offers on Win32.

I tried to implement a fast_recursive_mutex that adheres to the C++11 mutex concept and that fulfills all obligations according to spec. In all senses, it's a drop-in replacement for std::mutex as long as you're not synchronizing between processes.

It works great with std::lock_guard and std::unique_lock. However I encounter problems when trying to use it with std::condition_variable because std::condition_variable::wait(std::unique_lock<std::mutex>&) doesn't admit my fast_recursive_mutex due to the hard coded use of std::mutex.

So my questions are:

  1. Why does wait() not admit another mutex type than std::mutex?
  2. Is there something I can do about it? (Short of re-implementing condition_variable).
Emily L.
  • 5,673
  • 2
  • 40
  • 60
  • The first question of "why does it not admit another type", you may as well be asking why did they write two different `condition_variable` classes and not simply have one type with a templated mutex type. – CashCow Sep 02 '14 at 10:51

2 Answers2

6

You can use std::condition_variable_any for any lockable type.

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
-1

I believe std::mutex implementation in Visual Studio 2012/2013 already uses critical sections. Just check VSDIR\VC\crt\thr\mutex.c

You can also empirically check this using std::mutex::native_handle() method and cast what's returned to CRITICAL_SECTION.

kozmo
  • 51
  • 1
  • 4
  • 1
    Many people have measured this: http://stackoverflow.com/a/18092273/2498188 and http://stackoverflow.com/a/24470878/2498188 here for example. My own measurements agree with these.. – Emily L. Sep 02 '14 at 15:11
  • My point was VS doesn't literally use heavy weight ipc-capable mutexes but rather `Concurrency::critical_section` that somehow (check `critical_section::_Acquire_lock()` in VC\crt\src\rtlocks.cpp) is slower twice than `CRITICAL_SECTION`. – kozmo Sep 02 '14 at 15:48