试图将向量的内容传递给线程

时间:2014-07-26 14:05:34

标签: c++

我有一个带有字符串向量的函数,我在向量中有一系列字符串向量。

我想循环遍历将每个字符串向量传递给新线程的向量。

for (vector<vector<string> >::iterator it = vecstringvec.begin() ; 
     it != vecstringvec.end(); ++it){
    threadvector.push_back(thread(func, *it));
}

基本上是上面的,除了上面的不起作用(编译错误)。我相信我需要一个传递的std :: ref来传递,但我不确定,或者如何使用迭代器来做到这一点。

完整错误:

/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::vector<std::basic_string<char> >, std::reference_wrapper<std::vector<std::basic_string<char> > >))(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&)>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&); _Args = {std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&, std::reference_wrapper<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >}]’
prog.cpp:199:55:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::vector<std::basic_string<char> >, std::reference_wrapper<std::vector<std::basic_string<char> > >))(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&)>’
       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::vector<std::basic_string<char> >, std::reference_wrapper<std::vector<std::basic_string<char> > >))(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >&)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^
make: *** [prog.o] Error 1

1 个答案:

答案 0 :(得分:7)

查看错误消息,func() vector参数是pass-by-reference,而不是pass-by-value。尝试使用std::ref(*it)

引用cppreference

  

线程函数的参数按值复制。如果一个   引用参数需要传递给线程函数,它具有   被包装(例如用std :: ref或std :: cref)。

示例:

#include <vector>
#include <thread>
#include <iostream>

void func(const std::vector<int>& value)
{
    std::cout << "Value: " << value.size() << std::endl;
}

int main(int argc, char const *argv[])
{
    std::vector<std::vector<int>> values = 
        { { 1, 2 } , { 1, 2, 3 }, { 1, 2, 3, 4 } };

    std::vector<std::thread> threads;
    for (auto& vect: values)
    {
        threads.emplace_back(func, std::cref(vect));
    }

    for (auto& thread: threads)
    {
        thread.join();
    }

    return 0;
}

(顺便说一句,使用完整的自包含示例,诊断会更容易。)