[C++] manage background threads with boost::thread

#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>

typedef boost::function<void()> ThreadFunc;
void InvokeBackgroundThread(ThreadFunc f) {
    while(true) {
        try {
            boost::this_thread::interruption_point();
            f();
        } catch(boost::thread_interrupted const&) {
            std::cout << "Will Quit : " << boost::this_thread::get_id() << std::endl;
            break;
        }
    }
}

void PrintWork() {
    std::cout << __FUNCTION__ << "Id:"<< boost::this_thread::get_id() << std::endl;
    boost::this_thread::sleep_for(boost::chrono::seconds(2));
}

int main(int argc,char* argv[]) {
    
    std::vector<boost::thread> thread_pool;
    for(int index=0; index<2; index++) {
        ThreadFunc thread_func(PrintWork);
         boost::thread go_thread(boost::bind(InvokeBackgroundThread,thread_func));
         thread_pool.push_back(boost::move(go_thread));
    }


    std::cout << "Main Go Sleep" << std::endl;
    boost::this_thread::sleep_for(boost::chrono::seconds(10));
    std::cout << "Main WakeUp" << std::endl;

    for(int index=0; index<2; index++) {
        thread_pool[index].interrupt();
    }

    for(int index=0; index<2; index++) {
        thread_pool[index].join();
    }

    std::cout << "Finish" << std::endl;
    return 0;
}
原文地址:https://www.cnblogs.com/lambdatea/p/3408539.html