Arpit
Arpit

Reputation: 4407

thread pool in constructor of C++ class is getting killed

I have the following code which is creating thread pool in the constructor of the class. Threads got created and exited immediately. Please help.

class ThreadPool {
public:
    boost::asio::io_service io_service;
    boost::thread_group threads;
    ThreadPool();
    void call();
    void calling(); 
};

ThreadPool::ThreadPool() {
    /* Create thread-pool now */
    size_t numThreads = boost::thread::hardware_concurrency();
    boost::asio::io_service::work work(io_service);
    for(size_t t = 0; t < numThreads; t++) {
        threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
    }
}

void ThreadPool::call() {
    std::cout << "Hi i'm thread no " << boost::this_thread::get_id() << std::endl;
};

void ThreadPool::calling() {
    sleep(1); 
    io_service.post(boost::bind(&ThreadPool::call, this));
}

int main(int argc, char **argv)
{
   ThreadPool pool;
   for (int i = 0; i < 5; i++) {
    pool.calling();
   }
   pool.threads.join_all();
   return 0;
}

Upvotes: 1

Views: 315

Answers (1)

Sven Nilsson
Sven Nilsson

Reputation: 1879

boost::asio::io_service::work work must be a member of the class, so it does not get destroyed.

class ThreadPool {
public:
    boost::asio::io_service io_service;
    boost::thread_group threads;
    boost::asio::io_service::work *work;
    ThreadPool();
    void call();
    void calling(); 
    void stop() { delete work; }
};

ThreadPool::ThreadPool() :  work(new boost::asio::io_service::work(io_service)) {
    /* Create thread-pool now */
    size_t numThreads = boost::thread::hardware_concurrency();
    for(size_t t = 0; t < numThreads; t++) {
        threads.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));
    }
}

void ThreadPool::call() {
    std::cout << "Hi i'm thread no " << boost::this_thread::get_id() << std::endl;
};

void ThreadPool::calling() {
    Sleep(1000); 
    io_service.post(boost::bind(&ThreadPool::call, this));
}

int main()
{
   ThreadPool pool;
   for (int i = 0; i < 5; i++) {
    pool.calling();
   }
   pool.stop();
   pool.threads.join_all();
   return 0;
}

Upvotes: 2

Related Questions