开发者

Some questions regarding synchronization objects [Linux os]

开发者 https://www.devze.com 2023-02-06 21:00 出处:网络
I am very confused abou开发者_如何学运维t following statements.. \"Mutex is lightweight and faster than semaphore\"

I am very confused abou开发者_如何学运维t following statements..

  1. "Mutex is lightweight and faster than semaphore"
  2. "Semaphore use more memory than condition variable"

I have read somewhere that semaphore is based on system calls ..and it deals more with scheduler so its slow than mutex. but i am not getting it. Please help me clearing these concepts.

Thanx


Mutex and semaphore are two different things. Due to simplicity of a mutex it could be faster, but at the same time it serves a different purpose so comparing these two things is like comparing knife and riffle. Same goes for condition variables, they are just different. You can think of a semaphore as of mutex with conditions and a counter. Using those three objects you can implement the behavior of a semaphore. However, semaphores in POSIX can also be used to synchronize access to shared resources across processes, while mutex and condition are in-process only objects.

As for the lightweight and speed statements, I guess that depends on implementation. Semaphores in Linux are more complicated as they support inter-process synchronization, and mutex & condition are using futex subsystem with atomic operations. But again, comparing those things makes little to no sense as they serve different purposes.

I'd recommend you read the following on this subject:

  • Mutexes and Semaphores Demystified
  • Mutex vs Semaphore. The toilet example
  • Monitor, Semaphore and Mutual exclusion wiki pages.


Note, you are not restricted to mutexes, semaphores, or condition variables. You can also use straight up atomic operations. don't forget to Google "gcc atomic operations" too. BTW they are the fastest/lowest level way you can synchronize.

0

精彩评论

暂无评论...
验证码 换一张
取 消