【问题标题】:bind function parameters to thread将函数参数绑定到线程
【发布时间】:2011-06-11 11:10:31
【问题描述】:

我尝试使用 boost 调用带参数的函数,但它不起作用。代码是这样的

void Simulate::cr_number_threaded(lint nodes) {
    for(lint i = 0; i < trials_per_thread; i++) {
        // code
    }

}

void Simulate::run_cr_number() {
    vec_cr_number.clear();
    boost::thread t[threads];

    for(int i = 0; i < n_s.size(); i++) {
        // n_s[i] is the current number of nodes
        for(int t_idx = 0; t_idx < threads; t_idx++)
            t[t_idx] = boost::thread(cr_number_threaded, n_s[i]);
        // etc...
    }


}

我得到的错误如下:

Simulate.cpp:在成员函数'void 模拟::run_cr_number()': Simulate.cpp:27:错误:没有匹配 调用函数 'boost::thread::thread(, long int&)'

更新: 我听从了建议。使用我得到的第一个解决方案

Simulate.cpp:在成员函数'void 模拟::run_cr_number()': Simulate.cpp:28:错误:没有匹配 调用'bind(, long int&)'的函数 ../../boost_1_44_0/boost/bind/bind.hpp:1472: 注:候选人是: boost::_bi::bind_t::type> boost::bind(F, A1) [with F = void (模拟::*)(lint), A1 = long int] ../../boost_1_44_0/boost/bind/bind.hpp:1728: 注意:
boost::_bi::bind_t::type, boost::_mfi::dm, 类型名称 boost::_bi::list_av_1::type> boost::bind(M T::*, A1) [with A1 = 长整数,M = void ()(lint),T = 模拟]

使用第二个我得到了这个

Simulate.cpp:在成员函数'void 模拟::run_cr_number()': Simulate.cpp:28:错误:没有匹配 调用函数 'boost::thread::swap(boost::_bi::bind_t, boost::_bi::list2, boost::_bi::value > >)' ../../boost_1_44_0/boost/thread/detail/thread.hpp:310:注意:候选人是:void boost::thread::swap(boost::thread&)

【问题讨论】:

    标签: c++ multithreading function boost


    【解决方案1】:

    1) boost::thread 不是copyable 而是swappable

    2)你需要指定成员函数并传递一个实例

    类似这样的:

    t[t_idx].swap(boost::thread(&Simulate::cr_number_threaded, this, n_s[i]));
    

    在这种情况下,您需要确保this 的寿命比线程长。

    【讨论】:

    • cr_number_threaded 是一个成员函数,因此您需要传递一个实例并完全限定其名称:boost::bind( &amp;Simulate::cr_number_threaded, this, n_s[i] )
    • 我没有得到编译错误使用这个:t[t_idx] = boost::thread(&Simulate::cr_number_threaded, this, n_s[i]);
    • @Banana:它使用这个构造函数 boost.org/doc/libs/1_44_0/doc/html/thread/… 为您执行 bind
    • @Banana:已更正,boost 线程最近添加了此功能
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 2013-10-18
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2017-03-11
    相关资源
    最近更新 更多