Thread Wait For Parent

后端 未结 5 414
一个人的身影
一个人的身影 2020-12-10 19:30

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

5条回答
  •  [愿得一人]
    2020-12-10 19:56

    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.

提交回复
热议问题