【发布时间】:2018-05-08 07:01:03
【问题描述】:
我有关于多线程的问题。我有一个相当大的项目,现在我正在编写一些 exe 客户端来使用所有这些代码。它涉及多线程和进程间通信。我的 main 看起来像这样:
int main(int argc, char** argv)
{
std::unique_ptr<CommunicationWrapper> wrapper;
wrapper = std::make_unique<CommunicationWrapper>(argv[1]);
wrapper->run();
return 0;
}
下面有一个类进行进程间通信,如下所示:
CommunicationEngine::CommunicationEngine()
: m_processingLoop(std::async(std::launch::async, [this]() { processingLoop(); }))
{}
CommunicationEngine::~CommunicationEngine()
{
m_processingLoop.wait();
}
//some long function that do a lot of stuff based on messages from anothre process
void CommunicationEngine::processingLoop() const
这段代码可以正常工作,但我想知道在调用析构函数时进行同步(等待)是否被认为是好的做法和好的设计?这种方法可能存在哪些缺陷?
【问题讨论】:
-
标准库做到了。如果
std::future的析构函数是最后一个引用在对std::async的调用中创建的共享状态的析构函数,并且该状态尚未准备好,则会阻塞。
标签: c++ multithreading oop thread-synchronization