c++ - Passing an array by reference to thread -


i have array needs passed multiple threads worked on. array size know @ compile time. here working reduction essentials function called directly, not via thread:

#include <thread>  template <class type> void function(type& data, std::size_t row, std::size_t column){     data[row-1][column-1]=2; }  int main(){     const int column(5),row(2);     std::array<std::array<int, column>, row> arr;     function(arr, row, column);     return data[row-1][column-1]; } 

the code returns 2, expected. if call function via

    std::thread worker(function<std::array<std::array<int,column>,row>>, arr, row, column); 

i following compiler error:

g++ testo.cpp -o testo -std=c++11 -lpthread in file included /usr/include/c++/4.8/thread:39:0,                  testo.cpp:2: /usr/include/c++/4.8/functional: in instantiation of ‘struct std::_bind_simple<void (*(std::array<std::array<int, 5ul>, 4ul>, int, int))(std::array<std::array<int, 5ul>, 4ul>&, long unsigned int, long unsigned int)>’: /usr/include/c++/4.8/thread:137:47:   required ‘std::thread::thread(_callable&&, _args&& ...) [with _callable = void (&)(std::array<std::array<int, 5ul>, 4ul>&, long unsigned int, long unsigned int); _args = {std::array<std::array<int, 5ul>, 4ul>&, const int&, const int&}]’ testo.cpp:13:82:   required here /usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::array<std::array<int, 5ul>, 4ul>, int, int))(std::array<std::array<int, 5ul>, 4ul>&, long unsigned int, long unsigned int)>’        typedef typename result_of<_callable(_args...)>::type result_type;                                                              ^ /usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::array<std::array<int, 5ul>, 4ul>, int, int))(std::array<std::array<int, 5ul>, 4ul>&, long unsigned int, long unsigned int)>’          _m_invoke(_index_tuple<_indices...>)          ^ 

i can change template

template <class type> void function(type data, std::size_t row, std::size_t column){     data[row-1][column-1]=2; } 

and compiler no longer complains, main returns 0 array no longer passed reference. appropriate first argument thread call correct template pass array reference, working when calling function directly?

your function expects reference array std::thread stores decayed copies of bound arguments. array-to-pointer decay results in prvalue of pointer type. fix, pass arr through std::reference_wrapper preserve type:

std::thread worker(..., std::ref(arr), row, column); 

you might want use lambda won't have explicitly pass template arguments:

std::thread worker([&arr]{ return function(arr, row, column); }); 

Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -