如何将函数参数传递给boost :: thread_groups :: create_thread()

Min*_*orm 9 c++ boost-thread

我是Boost.Threads的新手,我正在尝试理解如何将函数参数传递给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;
}
Run Code Online (Sandbox Code Playgroud)

这不会编译与以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

awe*_*oon 16

你不能将参数传递给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
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想使用boost::bind,可以这样使用boost::thread_group::add_thread():

threads.add_thread(new boost::thread(printPower, b, e));
Run Code Online (Sandbox Code Playgroud)


Pet*_*ter 5

为了更灵活,您可以使用:

-Lambda函数(C++ 11):C++ 11 中的lambda表达式是什么?

threads.create_thread([&b,&e]{printPower(b,e);});
Run Code Online (Sandbox Code Playgroud)

-Functors将参数存储为const引用.

struct PPFunc {
    PPFunc(const float& b, const float& e) : mB(b), mE(e) {}
    void operator()() { printPower(mB,mE); }
    const float& mB;
    const float& mE;
};
Run Code Online (Sandbox Code Playgroud)

-std :: bind(C++ 11)或boost :: bind