【问题标题】:How to pass function parameters to boost::thread_groups::create_thread()如何将函数参数传递给 boost::thread_groups::create_thread()
【发布时间】:2013-04-25 12:02:34
【问题描述】:

我是 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

我做错了什么?

【问题讨论】:

    标签: c++ boost-thread


    【解决方案1】:

    您不能将参数传递给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));
    

    【讨论】:

    • 后一种方法适合我的问题,因为我无法复制任何参数。但是,它会引发以下错误:/usr/local/boost_1_44_0/include/boost/thread/detail/thread.hpp: In member function âvoid boost::detail::thread_data&lt;F&gt;::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
    • @Mindstorm,嗯...带有add_thread 的代码对我有用(boost v1.53)。
    • @Mindstorm,关于避免复制:就像你已经说过的那样使用boost::cref。我已经更新了答案。
    • 太棒了!代码使用boost::bindboost::cref 编译并运行良好
    【解决方案2】:

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

    -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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多