Boost线程池

Boost线程池

Boost 线程池位于组件 asio 中,是一种固定大小的线程池。

class thread_pool :
  public execution_context

Types

NameDescription
executor_typeExecutor used to submit functions to a thread pool.
fork_eventFork-related event notifications.

Member Functions

NameDescription
get_executorObtains the executor associated with the pool.
joinJoins the threads.
notify_forkNotify the execution_context of a fork-related event.
stopStops 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_poolDestructor.

Protected Member Functions

NameDescription
destroyDestroys all services in the context.
shutdownShuts down all services in the context.

Friends

NameDescription
add_service(Deprecated: Use make_service().) Add a service object to the execution_context.
has_serviceDetermine if an execution_context contains a specified service type.
make_serviceCreates a service object and adds it to the execution_context.
use_serviceObtain 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值