Boost线程池
Boost 线程池
位于组件 asio 中,是一种固定大小的线程池。
class thread_pool :
public execution_context
Types
Name | Description |
---|---|
executor_type |
Executor used to submit functions to a thread pool. |
fork_event |
Fork-related event notifications. |
Member Functions
Name | Description |
---|---|
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
Name | Description |
---|---|
destroy |
Destroys all services in the context. |
shutdown |
Shuts down all services in the context. |
Friends
Name | Description |
---|---|
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 );
/* 将函数投放到线程池 */
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