Boost Thread 使用指南

boost::thread 

    boost::thread 是Boost库对thread的封装,隐藏了特定于操作系统的实现,提供给用户统一的接口,实现了跨平台,同时使用户从繁杂的thread的特定于操作系统的API中解脱出来,取而代之的是更易理解、更优美的对象。每个thread对象代表一个线程。

一. 使用boost::thread创建线程

由于每一个boost::thread对应一个线程,所以创建线程就是创建一个boost::thread对象。

template

thread(Callable func);

这里需要一个函数对象(函数指针、仿函数)

仿函数

struct callable

{

       void operator()(void)

       {

            std::cout << "In callable ..." << std::endl;

       }

};

boost::thread thread_call(struct callable);

B.全局函数

void func()

{

     std::cout << "In fun..." << std::endl;

}

boost::thread thread_func(func);

C. 类成员函数

借助boost::bind 轻松实现

class thread_test

{

      public:

             void invoke()

             {

                  std::cout << "In thread_test::invoke..." << std::endl;

             }

};

thread_test athread_test;

boost::thread thread_member_call(boost::bind(&thread_test::invoke,&athread_test));

D. 含参函数对象

void func_arg(int num)

{

     std::cout << "In func_arg ..." << " num=" << num << std::endl;

}

boost::thread thread_arg_bind(boost::bind(&func_arg,1012));

boost::thread thread_arg(func_arg,2012);

Boost::thread 中重载的构造

template 

thread(F f,A1 a1,A2 a2,...);

其实他内部也是通过boost::bind创建函数对象。

thread(boost::bind(f,a1,a2,...))

二. 线程的管理

A. 线程标识符

boost中也有唯一标识线程的数据结构:thread::id

boost::thread thread_func(func);

thread::id var_id = thread_func.get_id()

cout << var_id (thread::id 重载了ostream);

B. 线程的分离与非分离

Boos::thread线程的默认属性为非分离状态,线程结束后线程标识符、线程退出状态等信息需要通过join方法回收。

boost::thread thread_func(func);

thread_func.join();

Join方法会阻塞,直到该线程执行结束。

Join函数是boost::thread中少数几个会抛出异常的方法之一。

join函数过程中如果 interrupt() 方法被调用,join函数会抛出一个boost::thread_interrupted异常。例外bool timed_join(TimeDuration const& rel_time);方法阻塞特定的时间,如果超时了但线程仍未退出,则返回false

当用户并不关心线程的退出状态时,可以设置thread状态为分离,这样boost::thread会自动回收线程资源。

boost::thread thread_func(func);

thread_func.detach();

bool joinable() 方法返回线程是否是分离状态。

线程的休眠和中断

boost::thread 中提供一个静态方法

void boost::thread::leep(system_time const& abs_time);

线程将休眠直到时间超时。

sleep 函数是boost::thread中少数几个可能抛出异常的方法之一:

sleep休眠期间interrupt() 方法被调用,sleep会抛出一个boost::thread_interrupted异常。

去了sleep()boost::thread提供一个void yield();方法主动放弃当前的CPU时间片。

D. 线程组

#include 

class thread_group:

    private noncopyable

{

public:

    thread_group();

    ~thread_group();

    template

    thread* create_thread(F threadfunc);

    void add_thread(thread* thrd);

    void remove_thread(thread* thrd);

    void join_all();

    void interrupt_all();

    int size() const;

};

例子:

thread_group var_thread_group;

//! 利用thread_group创建线程

boost::thread* pthread_one var_thread_group.create_thread(func);

//!加入线程组

var_thread_group.add_thread(pthread_one);

var_thread_group.add_thread(var_thread_group.create_thread(struct callable));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值