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

时间:2013-05-01 13:27:33

标签: 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;
}

这不会编译时出现以下错误:

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

我做错了什么?

2 个答案:

答案 0 :(得分: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

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

threads.add_thread(new boost::thread(printPower, b, e));

答案 1 :(得分:5)

为了获得更大的灵活性,您可以使用:

-Lambda函数(C ++ 11):What is a lambda expression in C++11?

threads.create_thread([&b,&e]{printPower(b,e);});

- 将参数存储为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;
};

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