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.

peterjtk
  • 41
  • 1
  • 7
  • 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? – Cameron Nov 26 '14 at 23:26
  • Does it even compile?!? (Oh, are you on a Microsoft compiler?) – Kerrek SB Nov 26 '14 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 – peterjtk Nov 27 '14 at 00:30

1 Answers1

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

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • The accepted answer [here](http://stackoverflow.com/questions/5116756/difference-between-pointer-and-reference-as-thread-parameter) describes that – vmg Nov 26 '14 at 23:29