Is it safe to declare a mutex as a static file-scoped variable?
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);
ret开发者_如何学编程urn 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.
This is an error in DLLs. It's risky in EXEs. If CMyClass::Foo()
is called during the initialization of another object with static storage duration (such as CMyClass::CMyClass
initializing the singleton), that call may precede the initialization of g_hMutex
. There's no global order in which objects are initialized.
The code as written will not get into a situation where someone closes the handle while someone is waiting on it because you never close the handle. The handle will be closed after the process terminates, but you're not waiting on it (that particular handle) then by definition.
HANDLE
doesn't have a non-trivial destructor so it will not close itself. Which of course can be problematic in and of itself, but that's a different problem from closing the handle too soon which you seem to be concerned about. I would suggest you take a step back and make sure you understand what you're trying to accomplish.
精彩评论