Boost threads - passing parameters by reference

拜拜、爱过 提交于 2019-12-06 06:37:02

问题


My application has a section that resembles the following code

void SomeClass::OtherMethod(std::vector<std::string>& g)
{
  g.pushback("Something");
}

void SomeClass::SomeMethod()
{
  std::vector<std::string> v;
  boost::thread t(boost::bind(&SomeClass::OtherMethod,this,v)
  t.join();
  std::cout << v[0]; //Why is this empty when the vector created on stack
}

I wanted to know why the vector v is empty when the vector is created on the stack and it works when it is created on the heap. I was expecting the above code to work since the vector remains in scope even when it is created on the stack.


回答1:


Bind copies its parameters. Use boost::ref:

boost::thread t(boost::bind(&SomeClass::OtherMethod,this, boost::ref(v))



回答2:


A thread by default takes arguments by value, even if the function itself expects a reference. Use boost::ref() to force passing argument by reference.

() by default the arguments are copied into internal storage, where they can be accessed by the newly created thread of execution, even if the corresponding parameter in the function is expecting a reference.

A. Williams, "Concurrency in Action", 2.2 Passing arguments to a thread function.



来源:https://stackoverflow.com/questions/17219508/boost-threads-passing-parameters-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!