

This is useful for representing a specific number of resources that are to be controlled/protected. Now that we’ve established at least one use-case for semaphores, recall that, unlike mutexes, semaphores incorporate a built-in counter (a signed integer) that is typically initialized to some value N, where N is usually ≥ 1. I like this example better than the usual example of bathrooms and keys, because the issue of which key works in which bathroom confuses the example. If there are no phone books available, you must wait until someone returns one of them to the stack. When you’re done with it, you “give” it back. If there are phone books available in the stack, you can “take” one.

The stack of phone books, not the phone books themselves, is the semaphore. If you want to place a call, you need a phone book to look up the number. Suppose that you are in an office with just 10 phone books (and no Internet). Semaphores are analogous to the classic, but outdated, example of phone books. If you’ve been using flags, variables and super loops to react to changes and control events in your code, skillful use of mutexes, semaphores and threads can improve your work.
#Semaphor technique code
Their use is considered a best practice among experienced firmware engineers, because they can make code more intuitive, leading to better maintainability, improved logic flow and higher productivity. This two-part series addresses the use and misuse of two of the most essential synchronization primitives in modern embedded systems, the mutex ( Part 1) and the semaphore (this article). Mutexes and semaphores are provided by most current RTOSs, although they can be implemented on bare-metal systems as well.
