Can Semaphore cause race condition?

Viewed 503

I am a student, currently studying operating system's concurrency - semaphore. I read books and read articles about semaphores, mutex & semaphores... but can't seem to answer title's condition.


There exists a semaphore, and semaphore can be used as "Binary semaphore" and "Counting semaphore" which is classified by initial value. I understand binary semaphore can prevent race condition by acting similarly as mutex(but two are not the same by various reasons.)

What i am curious about is that when we initialize the semaphore's value of more than or equal to 2, let's say n, then n values can enter the critical session. Then does this use of semaphore cause race condition?

I read articles about counting semaphores and it is considered that they are considered to keep track of the access to resources, and I'm confused about do we not use counting semaphore like this, and is counting semaphore not used to solve concurrency problems?


added below because my questions weren't detailed.

For example, when there are 100 threads, and I initialize X=10, then initialize semaphore with sem_init(&s, 0, X), and if there is a critical session in threads' code flow, then doesn't it induce race condition because 10 threads are allowed to use resources and do through the threads' flow?

2 Answers

Semaphores prevent race conditions. Counting semaphores are used where there is more than one instance of the resource that they control available.

If they control access to a single resource, then a mutex semaphore will be used. If there are two resources that can be used then a counting semaphore of two will be used. If there are three, then a semaphore of three will be, and so on.

What i am curious about is that when we initialize the semaphore's value of more than or equal to 2, let's say n, then n values can enter the critical session. Then does this use of semaphore cause race condition?

You are talking about a counting semaphore which generally gets initialized to 0. I actually can't think of a use case where you'd want to initialize it to a value >0 because each waiting thread/task will cause the counting semaphore to increment as long as it's waiting. Also the increments are atomic instructions and will not cause concurrency problems.

Related