According to http://msdn.microsoft.com/en-us/library/ms687032%28v=vs.85%29.aspx, WaitForSingleObject() has undefined behavior if a handle gets closed while waiting on it.
Because we can’t tell the order by which static variables are disposed, is it safe to declare a mutex as a static variable with 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!
I would be very leery about calling any Win32 API function at namespace scope. Also, since you have to release it in your function anyway, why not allocate it there too? It’s much more symmetrical that way.