【发布时间】:2016-05-10 07:12:10
【问题描述】:
c++ win 32 应用程序。对比 2013 我正在使用第 3 方库。 我想在后台线程中调用 3rd 方库的函数。 然后我也想最终将其关闭。 我怀疑在我存在应用程序之前我没有给第三方足够的时间来正确关闭自己。 如何确保在退出 main() 之前完成在单独线程上启动的分离任务。
//this class interfaces with the third part and runs on a separate thread
class ThirdParty
{
void Start(std::string filename)
{
MyApplication application;
FIX::SessionSettings settings(filename);
FIX::FileStoreFactory storeFactory(settings);
FIX::ScreenLogFactory logFactory(settings);
FIX::SocketAcceptor acceptor(application, storeFactory, settings, logFactory);
acceptor.start(); //this third party internally starts new threads and does stuff thats transparent to consumer like myself.
while (m_runEngine)
{}
//this shutsdown a few things and cant execute instantaneously
//This does not finish execution and main() already ends.
acceptor.stop();
}
void Stop()
{
m_runEngine = false;
}
private:
bool m_runEngine{ true };
}
这是我在 win32 应用程序中的 main()
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring arg = argv[1];
std::string filename = std::string(arg.begin(), arg.end());
ThirdParty myprocess;
std::thread t(&ThirdParty::Start, &myprocess, filename);
t.detach();
while (true)
{
std::string value;
std::cin >> value;
if (value == "quit")
break;
}
myprocess.Stop(); //This line will execute really fast and application will exit without allowing acceptor.stop() to properly finish execution
//How can I ensure acceptor.stop() has finished execution before I move on to the next line and finish the application
return 0;
}
【问题讨论】:
-
不要分离你的线程。相反,让它可以加入并在退出之前加入。更好的是,由于您在 Windows 上,因此获取本机线程句柄,在有意义的超时情况下等待其上的事件,并在触发事件时加入。否则只报错退出。
-
我明白了。所以我调用 t.joinable() 而不是 t.detach(),然后最后在 myprocess.stop() 之后调用 t.join()?这似乎在我的调试器中有效。我也会尝试其他选项。
-
不需要调用 t.joinable(),你知道它是可加入的。本机连接的问题在于,如果您的线程没有响应(陷入循环、锁定资源等),您的应用程序也会被卡住。这就是为什么值得给它一些时间来关闭它,但如果它不能,你就强行退出(有错误)。
-
不相关,但是有没有办法可以在主控制台窗口上显示来自同一解决方案的另一个项目中可能运行的另一个线程的消息?更新状态等
-
您应该能够简单地打印它们吗?抱歉,我对 Windows 不太熟悉。
标签: c++ multithreading