如何传递函数参数到boost :: thread_groups :: create_thread() [英] How to pass function parameters to boost::thread_groups::create_thread()
问题描述
我是新的 Boost.Threads ,我想了解如何传递函数参数到 boost :: thread_groups :: create_thread()
功能。阅读一些教程和增强文档后,我明白,可以简单地传递参数到这个函数,但我不能让这个方法工作。
I am new to Boost.Threads and am trying to understand how to pass function arguments to the boost::thread_groups::create_thread()
function. After reading some tutorials and the boost documentations, I understand that it is possible to simply pass the arguments to this function but I can't get this method to work.
我读的另一个方法是使用函子将参数绑定到我的函数,但是会创建参数的副本,我严格要求const引用传递参数将是大矩阵(这我计划通过使用 boost :: cref(Matrix)
一旦我得到这个简单的例子工作)。
The other method I read about is to use functors to bind the parameters to my function but that would create copies of the arguments and I strictly require that const references be passed since the arguments will be big matrices(this I plan to do by using boost::cref(Matrix)
once I get this simple example to work).
现在,让我们来看下面的代码:
Now, let's get down to the code:
void printPower(float b, float e)
{
cout<<b<<"\t"<<e<<"\t"<<pow(b,e)<<endl;
boost::this_thread::yield();
return;
}
void thr_main()
{
boost::progress_timer timer;
boost::thread_group threads;
for (float e=0.; e<20.; e++)
{
float b=2.;
threads.create_thread(&printPower,b,e);
}
threads.join_all();
cout << "Threads Done" << endl;
}
这不会编译出以下错误:
This doesn't compile with the following error:
mt.cc: In function âvoid thr_main()â:
mt.cc:46: error: no matching function for call to âboost::thread_group::create_thread(void (*)(float, float), float&, float&)â
/usr/local/boost_1_44_0/include/boost/thread/detail/thread.hpp: In member function âvoid boost::detail::thread_data<F>::run() [with F = void (*)(float, float)]â:
mt.cc:55: instantiated from here
/usr/local/boost_1_44_0/include/boost/thread/detail/thread.hpp:61: error: too few arguments to function
我做错了什么?
推荐答案
您不能将参数传递给 boost :: thread_group :: create_thread()
函数,因为它只有一个参数。您可以使用 boost :: bind
:
You can't pass arguments to boost::thread_group::create_thread()
function, since it gets only one argument. You could use boost::bind
:
threads.create_thread(boost::bind(printPower, boost::cref(b), boost::cref(e)));
# ^ to avoid copying, as you wanted
要使用 boost :: bind
,可以使用 boost :: thread_group :: add_thread()
p>
Or, if you don't want to use boost::bind
, you could use boost::thread_group::add_thread()
like this:
threads.add_thread(new boost::thread(printPower, b, e));
这篇关于如何传递函数参数到boost :: thread_groups :: create_thread()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!