将mutex声明为静态文件作用域变量是安全的吗? [英] Is it safe to declare a mutex as a static file-scoped variable?

查看:560
本文介绍了将mutex声明为静态文件作用域变量是安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http:// msdn。 microsoft.com/en-us/library/ms687032%28v=vs.85%29.aspx ,WaitForSingleObject()有一个未定义的行为,如果一个句柄被关闭,等待它。

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.

因为我们不能告诉静态变量的处理顺序,是否可以安全地将mutex声明为具有文件作用域的静态变量?

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;
}

谢谢!

推荐答案

在命名空间范围内调用任何 Win32 API函数,我将非常乐意。另外,既然你必须在你的函数中释放它,为什么不分配它呢?这是更对称的方式。

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.

这篇关于将mutex声明为静态文件作用域变量是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆