Subj : workq: condvar vs semaphore To : comp.programming.threads From : David Tiktin Date : Fri Aug 05 2005 02:01 pm This question was prompted by the "Win32 condition variables redux" thread and an older thread on thread pooling. I've been studying Dave Butenhof's workq.c implementation of a thread pool**. (Thanks, Dave!) Of course, he uses a pthread condvar. I recently wanted something similar, but I wanted it to be reasonably portable and I decided that convars aren't portable if you're include Win32, a view that seems to be vindicated by the recent thread on that subject and Q86 in the FAQ. I substituted a mutex protected queue and a semaphore since mutexes and semaphores are supported similarly (same basic logic) on all the platforms I'm interested in (Win32, Linux, Solaris, eCos). The task threads in the pool wait on the semaphore which starts with count 0. (In Win32, I set the maximum semaphore count to LONG_MAX.) The enqueuing task releases the semaphore once for each task it enqueues. Released threads dequeue a task, complete it, then go back to waiting on the semaphore. To stop all the threads, the enqueuing task empties the queue, sets a flag and releases the semaphore once for each thread (to simulate a broadcast). Pretty simple, and it seems to work ("seems" being the operable word when testing threaded code, but I also think it's correct). My question is about the design choice between the implementations. Is a mutex/semaphore implementation a reasonable replacement for convar in this case? If so, why did Dave choose a condvar? Is it just the right tool for the job? His implementation doesn't look like *just* sample code for the book! Is there a "better" scheme (implementing the same functionality but not involving a condvar) that would be "portable" in the sense that the *logic* is the same across the platforms I mentioned (even if the type and function names differ)? ** I found workq.c at: www.awprofessional.com/content/images/0201633922/sourcecode/workq.c BTW, I haven't read Dave's book (yet!), so I apologize if this is a topic he covers. Dave -- D.a.v.i.d T.i.k.t.i.n t.i.k.t.i.n [at] a.d.v.a.n.c.e.d.r.e.l.a.y [dot] c.o.m .