Reputation: 101
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?
Upvotes: 3
Views: 3095
Reputation: 1688
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.
Upvotes: 2
Reputation: 10396
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).
Upvotes: 6
Reputation: 39380
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.
Upvotes: 2