How to pass an argument to boost::thread?

╄→гoц情女王★ 提交于 2019-11-28 05:57:30

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

// 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

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:

void find_the_question(int the_answer);

boost::thread deep_thought_2(find_the_question,42);

Hope that helps.

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.

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

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

The bind and the function are unnecessary, and make the code slower and use more memory. Just do:

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

To add an argument just add an argument:

thread_ = boost::thread( &clientTCP::run , this, f );  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!