Boost.Thread库中boost::thread() 无启动参数的解决方法

博客展示了C++中自定义线程类LaThread的实现,包含线程的创建、启动、销毁等操作。还给出了继承该类的TestThread示例。重点介绍了boost::bind使函数满足boost::thread要求,以及解决相关问题的方法,开发者将在后续文档中加入说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Create only by new operator, delete by owner
 * joinable m_thread
 */
class LaThread {
   
private:
    boost::thread* m_thread;
 
    static static_run(LaThread* This) {
       This->run();
    }
 
protected:
    virtual void run() = 0;
 
public:
    LaThread() : m_thread(NULL) {}
    /**
     * Requires: threat ended
     */   
    virtual ~LaThread(){
       if( m_thread != NULL )
           delete m_thread;
    }
 
public:
    void start() {
       if( m_thread != NULL ) {
           throw std::exception(_T("m_thread != NULL"));
       }
       m_thread = new boost::thread( boost::bind(static_run, this) );
    }
 
    void join() {
       if( m_thread == NULL ) {
           throw std::exception(_T("m_thread == NULL"));
       }
       m_thread->join();
    }
};
 
class TestThread : public LaThread {
private:
    int arg;
public:
    TestThread( int arg ) {
       this->arg = arg;
    }
public:
    virtual void run() {
       _RPT3(_CRT_WARN, "[%d]/t[%s]/t[%s]/n", ::GetCurrentThreadId(), _T("Hi I'm new thread!"), __FUNCTION__);             
    }     
};
主要看点是:
new boost::thread( boost::bind(static_run, this) );
boost::bind使可以使 static_run(LaThread* This) 变成满足 boost::thread ( boost::function0 fuc )要求的函数。
C++ ISO 1998 的确并不是一个STL Container那么简单啊。还有boost::mem_fn呢。
解决这类别扭问题的方法的:
google: Boost Thread parameter
回复者(可能是Thread文档的开发者),说这样的说明将会加入到下个版本的文档中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值