美文网首页
Boost thread安全退出的一种方法

Boost thread安全退出的一种方法

作者: louyang | 来源:发表于2018-11-08 14:17 被阅读9次
    #include <iostream>
    #include <vector>
    #include <boost/thread.hpp>
    #include <boost/chrono.hpp>
    
    void thread_func(int a)
    {
        try {
            while (1) {
                std::cout << a << std::endl;
                boost::this_thread::sleep_for(boost::chrono::seconds(1));
            }
        }
        catch(boost::thread_interrupted const&)
        {
            std::cout << "thread " << a;
        }
    }
    
    int main()
    {
        std::vector<std::shared_ptr<boost::thread>> threads;
    
        std::cout << "main starts" << std::endl;
    
        for (int i = 0; i < 3; i++) {
            threads.push_back(std::make_shared<boost::thread>(thread_func, i));
        }
    
        boost::this_thread::sleep_for(boost::chrono::seconds(3));
        boost::posix_time::time_duration timeout = boost::posix_time::seconds(3);
    
        for (auto t : threads) {
            t->interrupt();
            if (t->timed_join(timeout))
            {
                std::cout << " finish correctly" << std::endl;
            }
            else
            {
                std::cout << "thread not finished" << std::endl;
            }
        }
    
        std::cout << "main ends" << std::endl;
        return 0;
    }
    

    运行

    # g++ d.cpp -lboost_thread && ./a.out
    main starts
    1
    0
    2
    1
    0
    2
    1
    0
    2
    thread 0 finish correctly
    thread 1 finish correctly
    thread 2 finish correctly
    main ends
    
    

    相关文章

      网友评论

          本文标题:Boost thread安全退出的一种方法

          本文链接:https://www.haomeiwen.com/subject/cflwxqtx.html