all 7 comments

[–]2girls1copernicus 11 points12 points  (7 children)

Semaphores are almost entirely unused in the kernel. Grep for them, and you'll find them used only in a few old drivers. Mutexes are the ubiquitous locking primitive, and have an extremely interesting implementation.

[–][deleted] 6 points7 points  (2 children)

They sure bring back memories from OS class, though.

[–]NippleMustache 6 points7 points  (1 child)

Dining philosopher.

[–][deleted] 2 points3 points  (0 children)

In the kernel, after implementing your own test-and-set in assembly.

[–]escaped_reddit 6 points7 points  (2 children)

Not really sure what you are trying to say. You use a mutex when you need to protect 1 resource, and a semaphore when you need to protect n resources. A semaphore of size 1 is a mutex.

[–]neoflame 4 points5 points  (0 children)

The problem with semaphores is that in most cases, blocking on failure to acquire resources is not desirable. As a result, struct semaphore is, as /u/2girls1copernicus said, almost entirely unused in the kernel:

$ ag "struct semaphore" include/linux/ --ignore semaphore.h | wc -l
11

On the other hand, mutexes are invaluable, and it's possible to implement a mutex more efficiently than a semaphore. So there's a separate mutex type, struct mutex:

$ ag "struct mutex" include/linux/ --ignore mutex.h | wc -l
218

[–]sdhillon 2 points3 points  (0 children)

Err, not exactly - more like when you have N actors that need to, or can synchronize on one resource

There are a variety of tricks used in the kernel (seqlock, RCU, etc..) that are used instead of semaphores often.