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

Gui*_*e07 19 c++ boost boost-thread

thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  
Run Code Online (Sandbox Code Playgroud)

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

void clientTCP::run(boost:function<void(std::string)> func);
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Mar*_*ram 31

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

// Pass pMyParameter through to the run() function
boost::bind(&clientTCP::run, this, pMyParameter)
Run Code Online (Sandbox Code Playgroud)

请参阅此处的文档和示例: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);
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


Adr*_*.S. 8

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

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


Jon*_*ely 7

thread_ = boost::thread( boost::function< void (void)>( boost::bind( &clientTCP::run , this ) ) );  
Run Code Online (Sandbox Code Playgroud)

bind function是不必要的,并且使代码更慢,使用更多的存储器.做就是了:

thread_ = boost::thread( &clientTCP::run , this );  
Run Code Online (Sandbox Code Playgroud)

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

thread_ = boost::thread( &clientTCP::run , this, f );  
Run Code Online (Sandbox Code Playgroud)