将向量元素的引用传递给线程函数

时间:2015-02-05 13:37:52

标签: c++ multithreading c++11 vector reference

我正在尝试做这样的事情:

#include <thread>
#include <vector>

void foo(bool &check){

}

int main(){
    std::vector<bool> vec(1);
    std::thread T(foo, std::ref(vec[0]));
}

不幸的是,gcc会抛出错误:

prog.cpp: In function 'int main()':
prog.cpp:10:34: error: use of deleted function 'void std::ref(const _Tp&&) [with _Tp = std::_Bit_reference]'
  std::thread(foo, std::ref(vec[1]))
                                  ^
In file included from /usr/include/c++/4.9/thread:39:0,
                 from prog.cpp:1:
/usr/include/c++/4.9/functional:453:10: note: declared here
     void ref(const _Tp&&) = delete;

但是它适用于普通变量:

bool var;
std::thread(foo, std::ref(var));

我不知道为什么我不能传递对vec元素的引用。有人可以解释原因吗?有没有解决方法?

2 个答案:

答案 0 :(得分:5)

问题是,您使用std::vector<bool>operator [] vector<bool>返回的不是bool,而是std::vector<bool>::reference,即代理类。 你可以使用类似的东西:

bool value = vec[0];
std::thread T(foo, std::ref(value));
T.join();
vec[0] = value;

答案 1 :(得分:0)

另一种解决方法(未经测试)

#include <thread>
#include <vector>

void foo(vector& v){
  //here access v[0] and assign whatever value you'd like
  //ideally you could pass an index as well
  // if you want to access the Nth element
}

int main(){
    std::vector<bool> vec(1);
    std::thread T(foo, std::ref(vec));
}