1

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.

3
  • Hmm, interesting. Don't pass a reference to the thread procedure, pass a pointer instead (or use a capturing lambda). Also, just curious, what benefit does using a thread give you if you wait for it to join synchronously? Or is this just sample code? Commented Nov 26, 2014 at 23:26
  • Does it even compile?!? (Oh, are you on a Microsoft compiler?) Commented Nov 26, 2014 at 23:26
  • just sample code the loop in the actual task will run until terminated and pass data (if there is anything to pass) every 100ms or so, the main loop is much faster ~1ms and needs to preform tasks on this time-scale. im using visual studio yeh Commented Nov 27, 2014 at 0:30

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

The accepted answer here describes that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.