加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C 11线程中等效的WAIT_ABANDONED

发布时间:2020-12-16 09:45:22 所属栏目:百科 来源:网络整理
导读:我正在重写使用WinAPI进行线程化以使用新标准线程库的代码. 我想知道C 11中的等效方式是注意到互斥量被遗弃或丢失了. 以下代码必须将初始化过程“外包”到创建的线程,但是在完成之前不应该返回并且知道初始化的结果. bool Foo::Example(){ m_thread = std::t
我正在重写使用WinAPI进行线程化以使用新标准线程库的代码.

我想知道C 11中的等效方式是注意到互斥量被遗弃或丢失了.

以下代码必须将初始化过程“外包”到创建的线程,但是在完成之前不应该返回并且知道初始化的结果.

bool Foo::Example()
{
    m_thread = std::thread(&Foo::ThreadProc,this);

    // wait for event before waiting for mutex
    WaitForSingleObject(m_hEvent,INFINITE);
    ResetEvent(m_hEvent);

    // the thread aquired the mutex. now wait until it is released or abandoned
    DWORD ret = WaitForSingleObject(m_hMutex,INFINITE);
    ReleaseMutex(m_hMutex);

    // check the result
    if (ret == WAIT_ABANDONED)
        return false;
    return true;
}
void Foo::ThreadProc()
{
    // aquire mutex and signal that it's done
    WaitForSingleObject(m_hMutex,INFINITE);
    SetEvent(m_hEvent);

    // ... initialization (required to be in this thread)

    if (initializationfailure)
        return; // failure. mutex is abandoned

    // success. mutex is unlocked
    ReleaseMutex(m_hMutex);

    // ... do the work
}

什么是WAIT_ABANDONED支票的替代品?我在std :: mutex中找不到任何东西.它甚至说如果互斥锁在被销毁之前没有被解锁,那么行为是未定义的,即一些线程仍然拥有它.没有等价物吗? std线程库中的任何东西都接近这个?

我还提出了改进代码的建议.这样一个简单的任务似乎太过同步了.

解决方法

没有等价物.您可以使用RAII来解锁互斥锁并避免首先放弃互斥锁,然后您就不需要能够对其进行测试.

您可以使用future而不是等待事件并使用互斥锁,这使得它比容易出错的显式同步更简单:

bool Foo::Example()
{
    std::promise<bool> p;
    auto res = p.get_future();
    m_thread = std::thread(&Foo::ThreadProc,this,std::ref(p));
    return res.get();
}
void Foo::ThreadProc(std::promise<bool>& p)
{
    // ... initialization (required to be in this thread)

    if (initializationfailure)
    {
        p.set_value(false); // failure.
        return;
    }

    p.set_value(true);

    // IMPORTANT: p is a dangling reference now!

    // ... do the work
}

主线程将阻塞,直到履行完成,然后根据初始化是否有效返回true或false.

您可以通过使其成为ThreadProc(std :: promise< bool> p)来避免悬空引用,然后将其作为std :: move(p)而不是std :: ref(p)传递,但我不认为std: :Visual C中的线程支持完全转发仅移动类型.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读