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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5730747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:44:09  来源:igfitidea点击:

How to pass an argument to boost::thread?

c++boostboost-thread

提问by Guillaume07

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

is it possible that run has an argument like this :

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

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

and if yes how my boost::thread call should be written

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

Thanks.

谢谢。

回答by Mark Ingram

The following code boost::bind( &clientTCP::run , this )defines a function callback. It calls the function runon the current instance (this). With boost::bind you can do the following:

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

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

See the documentation and example here:
http://www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html

请参阅此处的文档和示例:http:
//www.boost.org/doc/libs/1_46_1/doc/html/thread/thread_management.html

If you wish to construct an instance of boost::thread with a function or callable object that requires arguments to be supplied, this can be done by passing additional arguments to the boost::thread constructor:

如果您希望使用需要提供参数的函数或可调用对象来构造 boost::thread 的实例,可以通过将附加参数传递给 boost::thread 构造函数来完成:

void find_the_question(int the_answer);

boost::thread deep_thought_2(find_the_question,42);

Hope that helps.

希望有帮助。

回答by Adri C.S.

I just wanted to note, for future work, that Boost by default passes the arguments by value. So if you want to pass a reference you have the boost::ref()and boost::cref()methods, the latter for constant references.

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

I think you can still use the &operator for referencing, but I'm not sure, I have always used boost::ref.

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

回答by Jonathan Wakely

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

The bindandthe functionare unnecessary, and make the code slower and use more memory. Just do:

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

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

To add an argument just add an argument:

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

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