我是Boost.Threads的新手,正在尝试了解如何将函数参数传递给boost::thread_groups::create_thread()
函数。在阅读了一些教程和boost文档之后,我了解可以将参数简单地传递给该函数,但是我无法使该方法起作用。
我读到的另一种方法是使用仿函数将参数绑定(bind)到我的函数,但这将创建参数的拷贝,并且我严格要求传递const引用,因为参数将是大型矩阵(我计划使用boost::cref(Matrix)
进行此操作一旦我得到这个简单的例子就可以工作)。
现在,让我们看一下代码:
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;
}
这不会与以下错误一起编译:
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
:
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()
:threads.add_thread(new boost::thread(printPower, b, e));