Hey Daniweb,
I have recently started working with threads in the c++11 library. I started with a simple dispatch mechanism where I have a queue and that would get passed to the threads and the threads would take turns emptying the queue. Since each thread needs to share the queue I am passing it by reference. My original code looks likes this and it wasn't working.
// what DoTransactions looks like
void DoTransaction(std::queue<int> & line, std::vector<int> & customersServed, int wait)
//...
//...
std::queue<int> line;
for (int i = 1; i <= 10; i++)
line.push(i);
std::vector<std::vector<int>> returns(2);
std::vector<std::thread> threads;
for (int i = 0; i < 2; i++)
{
threads.push_back(std::thread(DoTransaction, line, returns[i], i + 1));
}
//...
I was able to find that I needed to wrap objects that I want to be passed as a refernce with std::ref()
and I got this
//...
for (int i = 0; i < 2; i++)
{
threads.push_back(std::thread(DoTransaction, std::ref(line), std::ref(returns[i]), i + 1));
}
//...
My question is do I always need to wrap an object with std::ref()
when I want to pass it by reference? Does this come from the fact that the call to std::thread
is a constructor and it doesnt forwar the references to the function the thread runs?