如何将参数传递给boost :: thread?

时间:2011-04-20 13:01:56

标签: c++ boost boost-thread

thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  

运行是否可能有这样的参数:

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

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

感谢。

3 个答案:

答案 0 :(得分:30)

以下代码boost::bind( &clientTCP::run , this )定义了函数回调。它在当前实例(run)上调用函数this。使用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);

希望有所帮助。

答案 1 :(得分:8)

我只想注意,对于未来的工作,默认情况下Boost按值传递参数。因此,如果您想传递引用,您可以使用boost::ref()boost::cref()方法,后者用于常量引用。

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

答案 2 :(得分:6)

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 );  
相关问题