Boost线程池
Boost線程池
Boost 線程池位于組件 asio 中,是一種固定大小的線程池。
class thread_pool :public execution_contextTypes
| executor_type | Executor used to submit functions to a thread pool. |
| fork_event | Fork-related event notifications. |
Member Functions
| get_executor | Obtains the executor associated with the pool. |
| join | Joins the threads. |
| notify_fork | Notify the execution_context of a fork-related event. |
| stop | Stops the threads. |
| thread_pool() | Constructs a pool with an automatically determined number of threads. |
| thread_pool(std::size_t num_threads) | Constructs a pool with a specified number of threads. |
| ~thread_pool | Destructor. |
Protected Member Functions
| destroy | Destroys all services in the context. |
| shutdown | Shuts down all services in the context. |
Friends
| add_service | (Deprecated: Use make_service().) Add a service object to the execution_context. |
| has_service | Determine if an execution_context contains a specified service type. |
| make_service | Creates a service object and adds it to the execution_context. |
| use_service | Obtain the service object corresponding to the given type. |
To submit functions to the thread_pool, use the dispatch , post or defer free functions.
#include <iostream> #include <thread> #include <boost/asio.hpp>/* 互斥鎖 */ std::mutex mutex_iostream;void my_task( void ) {std::lock_guard<std::mutex> lg(mutex_iostream);std::cout.flush();std::cout << "This is my task." << std::endl;std::cout.flush(); }int main( int argc, const char **argv ) {/* 定義一個4線程的線程池 */boost::asio::thread_pool tp( 4 );/* 將函數(shù)投放到線程池 */for( int i=0; i<5; ++i ) {boost::asio::post( tp, my_task );}/* 將語句塊投放到線程池 */for( int i=0; i<5; ++i ) {boost::asio::post(tp,[](){std::lock_guard<std::mutex> lg( mutex_iostream );std::cout.flush();std::cout << "This is lambda task." << std::endl;std::cout.flush();});}/* 退出所有線程 */tp.join();system("PAUSE");return 0; }Requirements
Header
- boost/asio/thread_pool.hpp
Convenience header
- boost/asio.hpp
總結(jié)
- 上一篇: 2019数学建模国赛Apython代码
- 下一篇: 2015 中国电商网站排行榜