【问题标题】:How to pass an argument to boost::thread?如何将参数传递给 boost::thread?
【发布时间】:2011-08-09 12:00:18
【问题描述】:
thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  

是否可能 run 有这样的参数:

void clientTCP::run(boost:function<void(std::string)> func);

如果是的话应该如何编写我的 boost::thread 调用

谢谢。

【问题讨论】:

    标签: c++ boost boost-thread


    【解决方案1】:

    以下代码boost::bind( &amp;clientTCP::run , this ) 定义了一个函数回调。它在当前实例 (this) 上调用函数 run。使用 boost::bind,您可以执行以下操作:

    // Pass pMyParameter through to the run() function
    boost::bind(&clientTCP::run, this, pMyParameter)
    

    在此处查看文档和示例:
    http://www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html

    如果你想构造一个实例 带有函数的 boost::thread 或 需要的可调用对象 要提供的参数,这可以是 通过传递额外的参数来完成 到 boost::thread 构造函数:

    void find_the_question(int the_answer);
    
    boost::thread deep_thought_2(find_the_question,42);
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      我只是想指出,对于未来的工作,Boost 默认按值传递参数。所以如果你想传递一个引用,你有 boost::ref()boost::cref() 方法,后者用于常量引用。

      我认为您仍然可以使用&amp; 运算符进行引用,但我不确定,我一直使用boost::ref

      【讨论】:

      • 这咬到我了。谢谢你。
      【解决方案3】:
      thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  
      

      bind function 是不必要的,会使代码变慢并占用更多内存。做吧:

      thread_ = boost::thread( &clientTCP::run , this );  
      

      要添加一个参数,只需添加一个参数:

      thread_ = boost::thread( &clientTCP::run , this, f );  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-16
        • 1970-01-01
        • 2020-12-15
        • 2010-10-16
        • 2016-04-16
        • 2021-04-24
        • 2013-02-21
        相关资源
        最近更新 更多