简体   繁体   中英

Semaphores vs. condition variables - level of abstraction

When I searched how I can use semaphores in C++11, I saw people often suggest that I make one out of a std::mutex and a std::condition_variable ( this post for example). This made me think that semaphores are a higher-level abstraction than mutexes and condition variables.

However, after I took our operation system class, I now know that in the kernel , semaphores are usually the lowest-level of abstraction. Semaphores are implemented by disabling interrupts, and locks are essentially semaphores with value 1, while condition variables are implemented from ground up without using semaphores or locks. So it seems semaphores (at kernel-level) are not in anyway a higher-level abstraction than locks or condition variables.

So my question is, is my conclusion that "semaphores (in C++11) are a higher-level abstraction" just an artifact of the limitation of the standard library? Or is it a result of the difference between user-level and kernel-level synchronization?

It is a result of the difference between user-level and kernel-level synchronization.

When you state in the kernel , you do not state which kernel you refer to. The standard library must be as agnostic as it can regarding the kernel, thus choosing the most common interface. Not all kernels implement locks the exact same way.

The implementation of locks in the Linux kernel, for instance, is quite more subtle than a basic semaphore initialized at value 1. Maybe you heard about futexes .

Finally, since semaphores usages are quite scarce compared to that of mutexes, it makes sense to choose mutexes as the common interface for the standard library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM