Question

Since the introduction of the thread library in C++11, I have been going through my code making some changes to move it away from platform specific multithreading code to portable standard library code.

However, I'm intrigued as to whether there is a performance or functionality difference between the standard library std::mutex and std::lock_guard<std::mutex> and the Win32 specific CMutex and CSingleLock.

I've no experience with profiling multithreaded code and I don't know the internals of either of the two mutex classes so I wouldn't even be able to hazard a guess.

Was it helpful?

Solution

Functionality deference is sure -- CMutex maps directly to Win32 mutex type while std::mutex is way more basic, likely implemented using win32 CRITICAL_SECTION removing the recursive nature and std::recursive_mutex wrapping CRITICAL_SECTION. Those would work similar to CCriticalSection.

CMutex is a heavyweight that in practice is used to create named mutexes for interprocess communication. You should not use it intraprocess.

If your question stand comparing recursive_mutex vs CCriticalSection, I'd bet on practically same performance. Interface-wise CSingleLock has completely braindead interface (it takes a second argument that defaults to FALSE instead of TRUE), so in practice I never used it directly only through macro to avoid mistake.

In new code I'd first try to solve things using std::future, and fiddle with locks only as last resort. The C++11 threading makes perfect sense to use, so until you need CMultiLock functionality it is better. I did not yet explore how to cover the latter case, but would be surprised if it can't be done easily.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top