Is it possible to implement C++11 mutex concept for use by std::condition_variable?
Asked Answered
C

2

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).
Caveat answered 2/9, 2014 at 10:28 Comment(1)
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.Waits
A
6

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

Amie answered 2/9, 2014 at 10:30 Comment(3)
Do you have any idea regarding the first question?Jointure
@anderas: #8758853Amie
I can't believe I missed this both when I looked at the references and when googling... Thanks!Caveat
S
-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.

Selfgovernment answered 2/9, 2014 at 15:1 Comment(2)
Many people have measured this: https://mcmap.net/q/1178568/-cost-of-mutex-critical-section-etc-on-windows and https://mcmap.net/q/351091/-std-mutex-performance-compared-to-win32-critical_section here for example. My own measurements agree with these..Caveat
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.Selfgovernment

© 2022 - 2024 — McMap. All rights reserved.