【问题标题】:thread pool in constructor of C++ class is getting killedC++ 类的构造函数中的线程池被杀死
【发布时间】:2017-03-24 09:43:24
【问题描述】:

我有以下代码在类的构造函数中创建线程池。线程被创建并立即退出。 请帮忙。

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;
}

【问题讨论】:

  • 你没有输出?
  • @Marco,没有输出。

标签: c++ c++11 boost boost-asio threadpool


【解决方案1】:

boost::asio::io_service::work work必须是类的成员,所以它不会被破坏。

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;
}

【讨论】:

  • 你说它不起作用是什么意思?在发布的代码中,您正在构造函数中创建一个工作对象,一旦构造函数完成,它就会被销毁,而 io_service 没有任何东西可以运行。
  • 我犯了一个愚蠢的错误,这就是为什么它对我不起作用..是的,它起作用了!谢谢!!
  • 你的例子有内存泄漏;你没有delete work 对象。
  • 完整示例没有泄漏,因为它调用了 stop()。但是你说得对,ThreadPool 的析构函数应该清理得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 2015-02-20
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
相关资源
最近更新 更多