C++ win 32アプリケーション。 VS 2013 私は第三者図書館を利用しています。 サードパーティライブラリの機能をバックグラウンドスレッドで呼びたいと思っています。 私はまた、最終的にそれをオフにしたいと思います。 私は、アプリケーションが存在する前に、サードパーティに十分な時間を与えないでください。 main()を終了する前に、別のスレッドで開始した分離タスクを確実に行う方法を教えてください。ここで C++アプリケーションを終了する前にバックグラウンドスレッドを終了させる
//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アプリケーションでは()私のメインである
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上にいるので、ネイティブスレッドハンドルを取得し、有意義なタイムアウトでイベントを待機し、イベントがトリガーされた場合に参加します。それ以外の場合は、エラーを報告して終了してください。 – SergeyA
私はそれを得る。 t.detach()の代わりにt.joinable()を呼び出し、最後にmyprocess.stop()の後にt.join()を呼び出します。それは私のデバッガで動作するようです。他のオプションも試してみます。 – bsobaid
t.joinable()を呼び出す必要はなく、joinableであることがわかります。ネイティブ・ジョインの問題は、スレッドが応答しなくなった場合(ループに詰まったり、リソースにロックされているなど)、アプリケーションが停止してしまうことです。これがシャットダウンする時間を与える価値がある理由ですが、できない場合は、forcefulyを終了してください(エラーが発生した場合)。 – SergeyA