Boost thread安全退出的一种方法

2018-11-08  本文已影响9人  louyang
#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

上一篇下一篇

猜你喜欢

热点阅读