I am implementing a simple thread pool mechanism for my ubuntu server (for my multi-client anonymous chat program), and I need to make my worker threads sleep until a job (i
Classical producer-consumer synchronization with multiple consumers (the worker threads consume work requests). The well-known technique is to have a semaphore, each worker thread does down()
and each time you have a work request, do up()
. Than pick the request from mutex-locked workqueue. Since one up()
will only wake up one down()
, there will actually be minimal contention on the mutex.
Alternatively you can do the same with conditional variable, doing wait in each thread and wake up one when you have job. The queue itself still locked with mutex (condvar requires one anyway).
Last I am not completely sure, but I actually think you can actually use a pipe as the queue including all synchronization (the worker threads simply trying to "read(sizeof(request))"). A bit hacky, but leads to fewer context switches.