David Mulder
David Mulder

Reputation: 8027

Using semaphores to prevent race conditions (in C)

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?

Upvotes: 2

Views: 7901

Answers (2)

subbul
subbul

Reputation: 947

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

Upvotes: 1

A Byas
A Byas

Reputation: 1

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)

Upvotes: 0

Related Questions