Implementing semaphore by using mutex operations and primitives

前端 未结 4 1015
后悔当初
后悔当初 2021-02-09 18:27

Some time ago had an interview and was asked to implement Semaphore by using mutex operations and primitives only (he allowed int to be considered as atomic). I came with soluti

4条回答
  •  醉酒成梦
    2021-02-09 19:00

    I'd wager this is not possible to implement without a busy-loop using mutexes only.

    If not busy-looping, you have to block somewhere. The only blocking primitive you've got is a mutex. Hence, you have to block on some mutex, when the semaphore counter is zero. You can be woken up only by the single owner of that mutex. However, you should woken up whenever an arbitrary thread returns a counter to the semaphore.

    Now, if you are allowed condition variables, it's an entirely different story.

提交回复
热议问题