Name and Unnamed Semaphore

Richard picture Richard · Oct 30, 2012 · Viewed 17.1k times · Source

I'm trying to understand the similarities and differences between named and unnamed semaphore so my google searches yielded me this. I had a question about the wording on the page though, it says:

  • Unnamed semaphores might be usable by more than one process
  • Named semaphores are sharable by several processes

Do those two words create any important distinction between those two types of semaphores or are they irrelevant?

So so far here's what I have:

Similarities
    -Several processes can do something with the semaphore

Difference
    -Named are referenced with pathname and unnamed are referenced by pshared value

That's all I could glean from that definition. Is that everything and are they correct? Or am I missing some significant concept?

Answer

Duck picture Duck · Oct 30, 2012

Think in terms of who can access the semaphore.

Unnamed semaphores (lacking any name or handle to locate them) must exist in some pre-existing, agreed upon memory location. Usually that is (1) shared memory (inherited by children after fork) in the case of child processes; or (2) shared memory, global variable or the heap in the case where they are shared between threads of a single process. The essential thing here is that the code in parent, child, or threads already knows the address of the semaphore.

Named semaphores are necessary for unrelated processes. For example a producer and consumer might be written by two different developers and run as completely unrelated processes. But they have to share some resource that needs to be protected by a semaphore. The named semaphore gives them a path to the semaphore.

In reality you can use a named semaphore in all scenarios but they come with a little extra baggage because you have to deal with the paths and permissions and such that are unnecessary if the programs are related and already know how to access an unnamed semaphore. It's a little silly, for instance, to use a named semaphore to share a resource between threads. The threads already have access to the same memory where an unnamed semaphore could reside.