I'm programming in Windows on c++ (Visual Studio) I can create mutex using either std::mutex or CreateMutex. What is the difference between them? Which one I should prefer and which one is faster? Do they have any specifics in usage or implimintation? or maybe std::mutex is just a shell and uses CreateMutex inside?
-
CreateMutex is a Win32 api function, while std::mutex is from C++ standard library. You can use CreateMutex instead of std::mutex, but the code will not be portable from Windows to Unix. – 23ars Apr 22 '16 at 08:34
-
1One is system independent and portable, the other is not. And it's not unlikely that `std::mutex` is a wrapper using the native Windows mutex primitives under the hood. – Some programmer dude Apr 22 '16 at 08:35
3 Answers
Besides the fact that std::mutex is cross platform and CreateMutex is not another difference is that the WinAPI mutexes (created through CreateMutex) can be used for synchronization between different processes, while std::mutex can not be used for that. In that sense std::mutex is more equal to the WinAPI Critical Section.
However there are also other things to consider, e.g. if you need to interoperate with std::condition_variable's or with WinAPI events (e.g. in order to use WaitForMultipleObjects).

- 9,836
- 1
- 20
- 29
-
Maybe std::mutex uses WinAPI Critical Section instead of CreateMutex inside? As I know Critical Section is much faster. – Artem Apr 22 '16 at 10:19
-
According to benchmarks reported at [A Windows mutex is not a mutex](http://www.sevangelatos.com/a-windows-mutex-is-not-a-mutex/), `std::mutex` is significantly faster than `CreateMutex` as a thread synchronization primitive. – MikeOnline May 13 '23 at 01:50
std::mutex
is provided by the C++ standard library and yes, most probably it will call CreateMutex
under the hood.
Since CreateMutex
is not portable, std::mutex
is generally preferred.

- 38,596
- 7
- 91
- 135
A difference in behavior is that CreateMutex
under Windows creates a recursive mutex, while std::mutex
is a non-recursive one. You'd have to use std::recursive_mutex
that was also added in C++11.

- 1,590
- 13
- 25