Is it safe to declare a mutex as a variable with a fixed file?

According to http://msdn.microsoft.com/en-us/library/ms687032%28v=vs.85%29.aspx , WaitForSingleObject () has undefined behavior if the handle closes while waiting.

Since we cannot determine the order of placement of static variables, is it possible to declare a mutex as a static variable with a file scope?

namespace { static HANDLE g_hMutex = CreateMutex(NULL, FALSE, NULL); } int CMyClass::Foo() //CMyClass is a singleton { int ret = 0; if (WaitForSingleObject(g_hMutex, 1000) != WAIT_OBJECT_0) return -1; //Do something ReleaseMutex(g_hMutex); return ret; } 

Thanks!

+4
source share
3 answers

I would be very careful in calling any Win32 API function in the namespace area. Also, since you should still release it in your function, why not select it there too? This is much more symmetrical.

+1
source

This is a bug in the DLL. This is risky in exe. If CMyClass::Foo() is called during initialization of another object with a static storage duration (for example, CMyClass::CMyClass initialization is singleton), this call may precede the initialization of g_hMutex . There is no global order in which objects are initialized.

0
source

Written code will not end up in a situation where someone closes the descriptor while someone is waiting for it because you never close the descriptor. The handle will be closed after the process is completed, but you will not wait for it (this particular descriptor) by definition.

HANDLE does not have a non-trivial destructor, so it will not close itself. This, of course, can be problematic in itself, but it is another problem that you close the handle too fast, which you seem to be worried about. I suggest you take a step back and make sure that you understand what you are trying to accomplish.

0
source

All Articles