将参数传递给boost :: thread中的函数

时间:2013-04-18 15:45:31

标签: c++ multithreading boost

这是我第一次使用boost thread函数,在此之前我对使用多个线程知之甚少。我尝试在初始调用的同时运行函数的第二个实例,这样我就可以将两个不同的变量传递给同一个函数,我希望能够加速我的程序。用我知道的代码我不断得到一个C2784错误,说

'T *boost::get_pointer(const boost::scoped_ptr<T> &)' : could not deduce template argument for 'const boost::scoped_ptr<T> &' from 'const std::string'

这是处理线程创建的代码片段

string firstPart = recText.substr(1,(subPart1-1));
string secondPart = recText.substr(subPart1,subPart1);

boost::thread firstThread;
boost::thread secondThread;

firstThread = boost::thread(&Conversion::conversion,firstPart);
secondThread = boost::thread(&Conversion::conversion,secondPart);
firstThread.join();
secondThread.join();

修改

void Conversion::conversion(string _Part)
{
int value_Part = 1;
int valueShort = 0;
int value = checkValue;
if(value == value_Part)
{
      // do stuff
    }
}

2 个答案:

答案 0 :(得分:4)

成员函数采用类型为隐式的第一个参数(cv qualified)T*,其中T是具有成员函数的类。您需要将指针传递给Conversion实例,例如

Conversion c;
firstThread = boost::thread(&Conversion::conversion, &c, firstPart);

答案 1 :(得分:0)

使用boost::bind

Conversion *conversion_obj_ptr = ...
boost::thread firstThread;
firstThread = boost::thread(boost::bind(&Conversion::conversion, conversion_obj_ptr, firstPart);

这假设Conversion :: conversion是一个成员函数。如果Conversion :: conversion不是成员函数,则省略conversion_obj_ptr参数。

修改

正如其他人所说,您不需要使用bindboost::thread构造函数会为您执行此操作。

http://www.boost.org/doc/libs/1_53_0/doc/html/thread/thread_management.html#thread.thread_management.thread.multiple_argument_constructor