So, this is a really simple question. I'm trying to use semaphores to prevent race conditions. I tried reading the man pages, but they are really confusing. Could someone provide a simple explanation how they work?
-
There's a good analogy on the following thread. http://stackoverflow.com/questions/34519/what-is-a-semaphore – David Z. Apr 20 '12 at 04:12
-
If you don't have the experience with parallel programming, yet, don't use semaphores. As you can see from the man pages they are interruptible, which makes them quite difficult to use in application code. Use mutexes, condition variables or read-write locks instead. – Jens Gustedt Apr 20 '12 at 06:34
2 Answers
I assume you are using in Linux/Unix. Semaphores are used to control/restrict the access to a shared resource (lets say a global variable) from multiple threads. One Thread can take semaphore, modify the value and release it If another thread tries to access the variable, it should acquire the semaphore, if its already aquired, it is pended and gains access after the previous thread relinquishes control.
This way semaphores are used for sequencing of operations and integrity of variables.
Semaphores are also used to signal events from one thread to another. Mutex are variants of semaphore, where the same thread acquires and release it (to protect critical section or race conditions)
read more details below
https://www.sao.ru/hq/sts/linux/doc/ipc_guide/semaphores.html

- 947
- 1
- 7
- 14
-
Subbul provides a good reference. Marc Rochkind in _Advanced Unix Programming_ remarked that semaphores are probably one of the most difficult things to use in Unix. When I used them, I stuck with single Dijkstra-like semaphores rather than taking advantage of the full complexity of Unix semaphores. – Alex Measday Apr 20 '12 at 09:57
-
The link in the answer is dead. The same page can be found on https://www.sao.ru/hq/sts/linux/doc/ipc_guide/semaphores.html – Garo Feb 13 '18 at 14:36
I am currently on this topic in my Systems II class, which basically uses C language for programming. As my instructor explained it to us, a semaphore is a non-negative integer synchronization variable which essentially helps to keep certain thread functions in check. It works somewhat like the pthread_mutex function which attempts to keep threads regulated within your code...ahem - yeah, I know that it is somewhat obscure, but all-in-all semaphores are used to regulate thread activity especially when utilizing relatively small buffers. Hope that I didn't confuse you more (0_0).
A couple of examples of what I mean:
– semaphore: non-negative integer synchronization variable.
• sem_wait(s): [ while(s==0) wait(); s--; ] – Originally named P(), Dutch for "Proberen" (test)
• sem_post(s): [ s++; ]
– Originally named V(), Dutch for "Verhogen" (increment)
– OS guarantees that operations between brackets [ ] are executed indivisibly.
CREDIT/CITATION: Dr. Phillips, Joseph, DePaul University, Lecture (2014)

- 1