我是新来的增强线程我试图了解如何将函数参数传递给boost::thread_groups::create_thread()
功能。在阅读了一些教程和 boost 文档后,我了解到可以简单地将参数传递给这个函数,但我无法让这个方法起作用。
我读到的另一种方法是使用函子将参数绑定到我的函数,但这会创建参数的副本,并且我严格要求传递 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));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)