C++ Threading/Ques

Soldato
Joined
7 Apr 2004
Posts
4,212
Hi,

I am after an example of how to set up 2+ threads and have some kind of thread safe task-que that both threads can monitor for tasks an act on them.

A little background info, each thread will be an open socket connection, and the que (if possible a vector) will contain tasks for the thread/connection to perform.

I would like to use C++ for this, so will probably be using the boost.threads library.

I just have never understood how to set up a system with multiple threads monitoring a single que. Would really appreciate it if anyone has a small skeleton program demonstrating how this sort approach works?

Thanks a lot,

Jack
 
So a master thread puts tasks into the queue, and the threads are supposed to retrieve them and perform them?

You probably want a condition variable (boost.thread provides a class implementing this). The basic idea is you have a condition variable object, upon which your threads wait (they sleep during this). The master thread puts task data into some shared memory, then signals the condition variable. This makes a thread wake from its sleep, and wait() returns. The thread can then access the task data, and use it.

You need some kind of boolean variable (predicate) to indicate whether or not there actually is data (which the worker threads reset to false when they consume the data), because signal() can sometimes wake more than one thread.

From what I can see, boost.thread's condvar is quite nice, because it handles the mutex relocking after wait() for you, which is otherwise a nasty/subtle trap you can get into.
 
Last edited:
Back
Top Bottom