gpt4 book ai didi

c++允许后台线程在退出应用程序之前完成

转载 作者:行者123 更新时间:2023-11-28 05:40:52 25 4
gpt4 key购买 nike

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;
}

最佳答案

不要让你的线程分离,这样你就可以使用thread::join()等待它结束:

//t.detach()   do not detach thread
...
myprocess.Stop();
t.join(); // wait for t to end

关于c++允许后台线程在退出应用程序之前完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com