tags:

views:

63

answers:

3

I have a worker thread which is alive from the start of the programme and would consistently take an object from a queue to process. I am wondering what is the best way to block the thread? The object would be pushed into the queue at about magnitude of every tens of microseconds( between 10 - 100 micro seconds). Should I set the thread to sleep at a constant period or should I work out some signalling mechanism between the threads? I would like mainly focusing on the performance issue. Any ideas?

Thanks.

A: 

Use POSIX message queues in blocking mode (mq_open, etc.), which is really simple, and see if they satisfy your performance requirements. If not, ask another question :)

zvrba
+1  A: 

On the other hand you could use condition variables as long as it is generic feature of pthreads. Condition variables is designed upon pthread mutexes so they are very effective sync primitives (depending on the actual platform of course).

Follow them.

Keynslug
That is exactly what condition variables are for. The consumer waits on the condition variable, and when a producer adds to the queue, it signals the condition variable to wake up the consumer.
Jonathan
+1  A: 

Posix message queues looks like a good candidate, if your data is not too big. You can also use a POSIX semaphore :

The producer thread put data on a queue, and do a sem_post
The consumer thread wait using sem_wait, and remove data from the queue.

It's easier to use IMO than condition variable. Of course you need to protect your queue. Depending on the size of the object, it might be more suited than message queues, but you need to implement your own queue.

Both can be used between process instead of thread. Should you decide to use process instead of thread, you could keep your synchronisation mechanism, which is not the case with condition variables.

shodanex