Thread Wait For Parent

后端 未结 5 427
一个人的身影
一个人的身影 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

    The easiest way to do this is semaphores. This is how a semaphore works:

    A semaphore is basically a variable that takes null/positive values. Processes can interact with it in two ways: increase, or decrease the semaphore.

    Increasing the semaphore adds 1 to this magical variable, and that's about it. It's in decreasing the count that things get interesting: if the count reaches zero and a process tries to lower it again, since it can't take negative values, it will block until the variable rises.

    If multiple processes block are waiting to decrease the semaphore value, only one is woken up for each unit the count is increased.

    This makes very easy to create a worker/task system: your manager process queues tasks and increases the value of the semaphore to match remaining items, and your worker processes try to decrease the count and acquire a task constantly. When no tasks are available, they'll block, and consume no cpu-time. When one appears, only one of the dormant processes will awake. Insta-sync magic.

    Unfortunately, at least in the Unix world, the semaphore API is not very friendly, since for some reason it deals with arrays of sempahores rather than individual ones. But, you're a simple wrapper away from a nice interface!

    Cheers!

提交回复
热议问题