pthreads mutex vs semaphore

后端 未结 9 1115
旧巷少年郎
旧巷少年郎 2020-12-12 11:31

What is the difference between semaphores and mutex provided by pthread library ?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 11:49

    I am going to talk about Mutex vs Binary-Semaphore. You obviously use mutex to prevent data in one thread from being accessed by another thread at the same time.

    (Assume that you have just called lock() and in the process of accessing a data. This means that, you don’t expect any other thread (or another instance of the same thread-code) to access the same data locked by the same mutex. That is, if it is the same thread-code getting executed on a different thread instance, hits the lock, then the lock() should block the control flow.)

    This applies to a thread that uses a different thread-code, which is also accessing the same data and which is also locked by the same mutex.

    In this case, you are still in the process of accessing the data and you may take, say, another 15 secs to reach the mutex unlock (so that the other thread that is getting blocked in mutex lock would unblock and would allow the control to access the data).

    Do you ever allow another thread to just unlock the same mutex, and in turn, allow the thread that is already waiting (blocking) in the mutex lock to unblock and access the data? (Hope you got what I am saying here.)

    As per agreed-upon universal definition,

    • with “mutex” this can’t happen. No other thread can unlock the lock in your thread
    • with “binary-semaphore” this can happen. Any other thread can unlock the lock in your thread

    So, if you are very particular about using binary-semaphore instead of mutex, then you should be very careful in “scoping” the locks and unlocks, I mean, that every control-flow that hits every lock should hit an unlock call and also there shouldn’t be any “first unlock”, rather it should be always “first lock”.

提交回复
热议问题