C++11 多线程,通过引用传递

标签 c++ multithreading c++11 reference

void _function_(std::vector<long long>& results){

    results.push_back(10);
    return ;
}


int main(){

    std::vector<std::thread> threads;
    std::vector<std::vector<long long>> results_array;
    for(int i=1;i<=N;i++){
    results_array[i]=std::vector<long long>();
    threads.push_back(std::thread(&_function_,results_array[i]));
    }

    for(auto& th : threads){
    th.join();
    }
    return 0;
}

这是 C++ 代码。我想使用std::vector<long long>保留每个线程的结果。所以我初始化一个 std::vector<std::vecotor<long long>>对于每个线程。然而,当通过results_array[i]时,我收到以下错误:

In file included from /usr/include/c++/5/thread:39:0,
                 from multi-thread.cc:3:
/usr/include/c++/5/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::vector<long long int>))(std::vector<long long int>&)>’:
/usr/include/c++/5/thread:137:59:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (*)(std::vector<long long int>&); _Args = {std::vector<long long int, std::allocator<long long int> >&}]’
multi-thread.cc:21:60:   required from here
/usr/include/c++/5/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<long long int>))(std::vector<long long int>&)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/5/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<long long int>))(std::vector<long long int>&)>’
         _M_invoke(_Index_tuple<_Indices...>)

我也尝试std::ref(results_array[i]) ,但存在塌陷故障。

有人可以帮我解决这个问题吗?谢谢!

最佳答案

这里的代码是正确的:

void _function_(std::vector<long long>& results){

    results.push_back(10);

    return ;

}

int main(){

    int N = 10;

    std::vector<std::thread> threads;

    std::vector<std::vector<long long>> results_array;

    for(int i=0;i<N;i++){

    results_array.push_back(std::vector<long long>());

    threads.push_back(std::thread(&_function_, std::ref(results_array[i])));

}

for(auto& th : threads){
th.join();
}
    return 0;
}

你的问题在这一行:

threads.push_back(std::thread(&_function_, std::ref(results_array[i])));

你没有得到 results_array 的引用。 哟还必须在这里更正

results_array.push_back(std::vector<long long>());

关于C++11 多线程,通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50460150/

相关文章:

.net - 从 IUnknown 实现接口(interface)类时出现错误 c2259

c++ - 无法通过 epoll-client 发送数据

java - final 关键字究竟对并发性有什么保证?

java - 当所有JAVA线程都是使用OS库创建的 native 线程时,为什么要引入Fork/Join框架?

c++ - 有没有办法调用纯虚类的 "deleting destructor"?

c++ - C++11中根据类型要求特化类模板成员函数

c++ - 在 C++ 中捕获并重新抛出异常

c++ - 文件处理,复制内容时插入 ÿ 字符

java - 以编程方式发现本地网络设备和 IO

c++类成员函数对bool值的特化