2011-04-20 63 views
18
thread_ = boost::thread(boost::function< void (void)>(boost::bind(&clientTCP::run , this))); 

是有可能,运行有这样一个参数:如何将参数传递给boost :: thread?

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

,如果是我的boost ::线程调用应该怎么写

感谢。

回答

27

以下代码boost::bind(&clientTCP::run , this)定义了函数回调。它调用当前实例上的功能runthis)。随着的boost ::绑定,你可以做到以下几点:

// 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 ::线程的实例 与功能或 需要提供参数 参数的可调用对象,这可以通过将其他参数 传递给boost :: thread构造函数完成,即 :

void find_the_question(int the_answer); 

boost::thread deep_thought_2(find_the_question,42); 

希望有帮助。

7

我只是想说明,对于未来的工作,默认情况下Boost会通过值传递参数。所以如果你想通过一个参考你有boost::ref()boost::cref()方法,后者用于不断的引用。

我认为你仍然可以使用&算子进行参考,但我不确定,我一直使用boost::ref

+0

这咬我。谢谢你。 – RandomInsano 2015-04-21 18:02:00

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

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

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

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

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