2016-11-10 48 views
0

我有以下代碼在類的構造函數中創建線程池。線程立即創建並退出。 請幫忙。C++類的構造函數中的線程池正在死亡

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

而你沒有輸出? – Marco

+0

@Marco,沒有輸出。 – Arpit

回答

2

的boost ::支持ASIO :: io_service對象::工作工作必須是類的成員,因此它不會被破壞。

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

我試過這個選項..但沒有運氣! – Arpit

+0

你是什麼意思,它不工作?在發佈的代碼中,您正在構造函數內創建一個工作對象,一旦構造函數完成,它就會被銷燬,離開io_service而無法運行。 – Arunmu

+1

我添加了整個代碼,經過測試並且可以正常工作。 –