首页 文章

将函数参数绑定到线程

提问于
浏览
0

我尝试使用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 Simulate :: run_cr_number()'中:Simulate.cpp:27:错误:没有用于调用'boost :: thread :: thread(,long int&)'的匹配函数

更新:我遵循了建议 . 使用我得到的第一个解决方案

Simulate.cpp:在成员函数'void Simulate :: 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(Simulate :: *)(lint),A1 = long int] ../../boost_1_44_0/boost/bind/bind.hpp:1728:注意:boost :: _ bi :: bind_t :: type,boost :: _ mfi :: dm,typename boost :: _ bi :: list_av_1 :: type> boost :: bind(MT :: *,A1)[A1 = long int,M = void()(lint),T = Simulate]

使用第二个,我得到了这个

Simulate.cpp:在成员函数'void Simulate :: 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 ::掉期(升压::线程和)

1 回答

  • 1

    1)boost :: thread不是 copyableswappable

    2)您需要指定成员函数并传递实例

    这样的事情:

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

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

相关问题