简体   繁体   English

Windows下C ++代码的同步API失败

[英]Failure in synchronization APIs for C++ code under Windows

If I define a template struct like so: 如果我像这样定义模板结构:

template <typename T> 
struct SYNCHED_DATA
{
    SYNCHED_DATA()
    {
        hMutex = ::CreateMutex(NULL, FALSE, NULL);
    }
    ~SYNCHED_DATA()
    {
        if(hMutex)
            CloseHandle(hMutex);
        hMutex = NULL;
    }

    void set(T* pV)
    {
        if(pV)
        {
            ::WaitForSingleObject(hMutex, INFINITE);
            var = *pV;
            ::ReleaseMutex(hMutex);
        }
    }
    void get(T* pV)
    {
        if(pV)
        {
            ::WaitForSingleObject(hMutex, INFINITE);
            *pV = var;
            ::ReleaseMutex(hMutex);
        }
    }

private:
    HANDLE hMutex;
    T var;

    SYNCHED_DATA(const SYNCHED_DATA& s)
    {
    }
    SYNCHED_DATA& operator = (const SYNCHED_DATA& s)
    {
    }
};

Can I be assured that those WaitForSingleObject() APIs will always return WAIT_OBJECT_0? 我可以确保那些WaitForSingleObject()API总是返回WAIT_OBJECT_0吗? And if no, in what circumstances can they fail and how am I supposed to handle it then? 如果不是,那么在什么情况下它们会失败,那么我应该如何处理呢?

The Old New Thing has an article on how closing the handle before the wait succeeded will result in WAIT_ABANDONED for anybody waiting: The Old New Thing上有一篇文章,内容涉及如何在等待成功之前关闭句柄,从而使等待的任何人都得到WAIT_ABANDONED

http://blogs.msdn.com/b/oldnewthing/archive/2005/09/12/463977.aspx http://blogs.msdn.com/b/oldnewthing/archive/2005/09/12/463977.aspx

There is some discussion of WAIT_FAILED on this very site: 这个站点上有一些关于WAIT_FAILED讨论:

Why would WaitForSingleObject return WAIT_FAILED 为什么WaitForSingleObject返回WAIT_FAILED

These suggest that failure is a possibility even with an infinite timeout. 这些表明即使无限超时也可能导致故障。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM