c++11 - thread pool in constructor of C++ class is getting killed -


i have following code creating thread pool in constructor of class. threads got created , 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 */     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;    (int = 0; < 5; i++) {     pool.calling();    }    pool.threads.join_all();    return 0; } 

boost::asio::io_service::work work must member of class, not 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 */     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;    (int = 0; < 5; i++) {     pool.calling();    }    pool.stop();    pool.threads.join_all();    return 0; } 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -