Reputation: 41
I'm looking for a way to pass a queue between threads in c++, below is a very basic outline what I want to do. It works as a function but I need to use a separate thread as both the task and main will have separate loops to perform.
here is the function:
void task1(queue <bool> &qPass)
{
bool bits[5] = { 1, 0, 0, 1, 1 };
for (int i = 0; i < 5; i++)
{
qPass.push(bits[i]);
}
cout << "Task:\tpush complete\t(" << qPass.size() << ")" << endl;
}
the main
int main()
{
queue <bool> qPass;
int n;
//thread task(task1, qPass);//thread call doesnt work
//task.join();
task1(qPass);//function call works
n = qPass.size();
cout << "Main:\t";
for (int i = 0; i < n; i++)
{
cout << qPass.front();
qPass.pop();
}
cout << "\t(" << n << ")" << endl;
cin.get();
return 0;
}
If I comment the function call and uncomment the thread calls it will run but the queue in main isn't filled. Thanks in advance.
Upvotes: 1
Views: 3256
Reputation: 476950
You need to wrap the argument in a reference wrapper:
std::thread task(task1, std::ref(qPass));
// ^^^^^^^^
(Otherwise, the thread objects binds a local, private copy of the queue, and your main queue is never touched.)
Upvotes: 3