C++ 相当于C++;11螺纹
我正在重写使用WinAPI进行线程处理的代码,以使用新的标准线程库 我想知道,在C++11中,注意到互斥被放弃或丢失的等效方式是什么 下面的代码必须将初始化过程“外包”给创建的线程,但在完成并知道初始化结果之前不应返回C++ 相当于C++;11螺纹,c++,multithreading,winapi,c++11,C++,Multithreading,Winapi,C++11,我正在重写使用WinAPI进行线程处理的代码,以使用新的标准线程库 我想知道,在C++11中,注意到互斥被放弃或丢失的等效方式是什么 下面的代码必须将初始化过程“外包”给创建的线程,但在完成并知道初始化结果之前不应返回 bool Foo::Example() { m_thread = std::thread(&Foo::ThreadProc, this); // wait for event before waiting for mutex WaitForSin
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
}
用什么来代替放弃的支票?我在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
}
boolfoo::Example()
{
std::promise p;
自动恢复=获取未来();
m_thread=std::thread(&Foo::ThreadProc,this,std::ref(p));
return res.get();
}
void Foo::ThreadProc(标准::promise&p)
{
//…初始化(需要在此线程中)
如果(初始化失败)
{
p、 设置_值(false);//失败。
返回;
}
p、 设置_值(真);
//重要提示:p现在是一个悬而未决的参考!
//…做这项工作
}
主线程将阻塞,直到承诺得到满足,然后根据初始化是否有效返回true或false
< >可以避免悬空引用,使其成为<代码> thREADPRC(STD::POUNTY P),然后传递为“代码> STD::移动(p)< /C> >代替
WAIT\u audded
状态为“哦,糟了,有些事情出了可怕的错误,最好现在就尽快退出”标志,而不是正常程序运行期间应该发生的事情。