C ++ 11 многопоточность, передавая по ссылке - PullRequest
0 голосов
/ 22 мая 2018
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]), но с ошибкой сагметации.

Может кто-нибудь помочь мне в этом вопросе?Спасибо!

1 Ответ

0 голосов
/ 22 мая 2018

Здесь у вас правильный код:

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>());

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...