c ++允许后退线程在退出应用程序

时间:2016-05-09 20:23:04

标签: c++ multithreading

c ++ win 32应用程序。 VS 2013 我正在使用第三方库。 我想在后台线程中调用第三方库的功能。 然后我也希望最终将其关闭。 我怀疑在我存在应用程序之前,我没有给第三方足够的时间来正确关闭自己。 在退出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;
}

2 个答案:

答案 0 :(得分:1)

不要让你分离线程,以便你可以等待thread::join()结束:

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

答案 1 :(得分:0)

我认为以下示例说明了线程连接的有趣方面。

void pause_thread(int n, std::string lbl)
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << lbl << " pause of " << n << " seconds ended" << std::endl;
}

int t403(void)  // in context of thread main
{
   std::cout << "Spawning 3 threads...\n" << std::flush;
   std::thread t1 (pause_thread, 3, "t1");
   std::thread t2 (pause_thread, 2, "t2");
   std::thread t3 (pause_thread, 1, "t3");
   std::cout << "Done spawning threads, "
      "Note that the threads finish out-of-order. \n"
      "Now 'main' thread waits for spawned threads to join:\n" << std::flush;

   t1.join(); std::cout << "join t1  " << std::flush;
   t2.join(); std::cout << "join t2  " << std::flush;
   t3.join(); std::cout << "join t3  " << std::flush;
   std::cout << "completed join \n"
      "note: \n - join sequence is in-order, but finish sequence is out-of-order\n"
      " - inference:  the threads waited in join main. "<< std::endl;

   return(0);
}

请注意,线程按顺序生成:t1,t2,t3。

请注意,线程的顺序不同。

但是加入仍然在启动顺序中,因为这是主要的等待。

使用&#39; std :: flush()&#39;提出了为人类视觉选择足够慢的时间线。