Question

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.

Was it helpful?

Solution

Bind copies its parameters. Use boost::ref:

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top