Semaphores in OS: Wait, Signal, Test-and-Set & Synchronization Explained

Operating System Chapter 7 · Semaphore Control Console
Semaphores in OS: Wait, Signal, Test-and-Set & Synchronization Explained

A semaphore is a synchronization variable used to control access to shared resources and coordinate the order of concurrent processes or threads. The two basic operations are wait() and signal(). wait() requests or consumes permission; signal() releases permission or wakes a waiting process. A binary semaphore can protect one critical section, while a counting semaphore can represent several identical resources. Semaphores can be implemented using blocking queues so waiting processes do not waste CPU time. Test-and-set is different: it is an atomic hardware instruction often used to build low-level locks. This chapter teaches all of these ideas through simple resource-permit examples, solved traces and synchronization patterns.

Semaphore wait() / P / down signal() / V / up Binary semaphore Counting semaphore Test-and-set
Start from the problem

Why Do We Need a Semaphore?

Semaphores in OS: Wait, Signal, Test-and-Set & Synchronization Explained

Suppose two processes want to update the same shared variable. If both enter the sensitive code at the same time, one update can overwrite the other.

Process P1

Reads shared counter and prepares an update.

SAME
RESOURCE

Process P2

Reads and updates the same counter at nearly the same time.

This is the same race-condition problem studied in Critical Section & Mutual Exclusion in OS.

A semaphore gives the operating system a controlled way to say “you may enter,” “you must wait,” or “a resource has become available.”

Think in permits

Semaphore Meaning With a Simple Permit Example

The easiest way to understand a semaphore is to imagine a box of permits.

Process wants resource It performs wait().
3available permits
Process finishes It performs signal().

If the semaphore value is 3, up to three resource units are available. Every successful wait() takes one permit. Every signal() returns one permit.

Semaphore value = available permission/resource count
Core operation 01

What Does wait() Do?

wait(S)

wait() tries to acquire permission from semaphore S.

If permission is available: take one permit continue If permission is not available: wait according to the semaphore implementation

signal(S)

signal() returns permission to semaphore S and may wake a waiting process.

Release one permit If a process is waiting: make one waiting process eligible to continue

Textbooks also use other names:

wait()Also called P, down or acquire in different contexts.
signal()Also called V, up or release in different contexts.

The exact pseudocode can differ between textbooks and operating systems, but the idea is always permission acquisition and release.

The classic synchronization recipe

How Is a Semaphore Used Around a Critical Section?

1. wait()Request entry
2. EnterPermission acquired
3. Critical SectionUse shared resource
4. signal()Release permission
wait(S) -> critical section -> signal(S)

For mutual exclusion, the semaphore is commonly initialized to 1. That single permit ensures only one process enters the protected section at a time.

Type 01

What Is a Binary Semaphore?

Binary Semaphore

A binary semaphore represents two logical states: permission available or permission unavailable.

Typical use: mutual exclusion or simple event synchronization.

Counting Semaphore

A counting semaphore represents multiple available units of a resource.

Typical use: controlling access to a pool of identical resources.

A binary semaphore is often initialized to 1 when used for mutual exclusion.

Binary semaphore for mutual exclusion: initial value = 1
Type 02

What Is a Counting Semaphore?

A counting semaphore is used when more than one identical resource instance is available.

Imagine a lab with three printers. At most three print jobs can use a printer at the same time.

Semaphore S = 3
Printer 1
Printer 2
Printer 3
After two wait()
Printer 1 busy
Printer 2 busy
Printer 3 free

If all three permits are taken, the next process must wait until one process executes signal().

Solved trace 01

Binary Semaphore Example Step by Step

Suppose:

S = 1
P1 executes wait(S)P1 takes the only permit and enters the critical section.
S becomes unavailableNo second process should enter the same protected section now.
P2 executes wait(S)P2 cannot enter, so it waits according to the semaphore implementation.
P1 executes signal(S)The permit is released.
P2 continuesP2 can now acquire permission and enter.

This is semaphore-based mutual exclusion.

Solved trace 02

Counting Semaphore Example Step by Step

Suppose a system has three identical database connections available:

S = 3
P1 performs wait()One connection is taken. Two remain.
P2 performs wait()A second connection is taken. One remains.
P3 performs wait()The last free connection is taken.
P4 performs wait()No connection is free, so P4 waits.
P2 performs signal()A connection is returned, so a waiting process can continue.
Blocking implementation

What Happens When Semaphore Permission Is Not Available?

A practical semaphore can place the process into a waiting queue instead of letting it waste CPU time.

P1Owns permit
P2Waiting
P3Waiting
P4Waiting
signal()Wake/allow next

With a blocking semaphore, a waiting process can sleep instead of repeatedly checking the semaphore value. When another process signals, one waiting process can become ready again.

Blocking wait = sleep instead of wasting CPU in a loop
Busy wait vs blocking

Busy-Wait Semaphore vs Blocking Semaphore

PointBusy WaitingBlocking
Waiting behaviorRepeatedly checks conditionProcess sleeps/waits in a queue
CPU usage while waitingConsumes CPU cyclesMuch lower while blocked
Useful whenExpected wait is extremely shortWait may be longer
Typical formSpinlock-like behaviorSemaphore/mutex with scheduler support

This distinction matters because semaphore theory is about synchronization, while the exact waiting mechanism is an implementation choice.

Ordering, not just exclusion

How Can Semaphores Control Execution Order?

Semaphores can do more than keep two processes out of the same critical section. They can also enforce “this must happen before that.”

Suppose P2 must not start Step B until P1 finishes Step A.

Initialize S = 0
P2 calls wait(S)Because no signal has happened yet, P2 waits.
P1 performs Step AThe required earlier action completes.
P1 calls signal(S)This releases the synchronization event.
P2 continuesNow P2 can perform Step B.

This is synchronization by ordering: semaphore value 0 is useful when one process must wait for an event from another process.

A key comparison

Semaphore vs Mutex

PointSemaphoreMutex
Main ideaPermit/counter for synchronizationOwnership-based mutual exclusion lock
ValuesBinary or countingLocked or unlocked
Resource countCan represent multiple resourcesUsually protects one critical section/resource
Ordering useCan coordinate event orderMainly protects exclusive ownership
Ownership conceptNot always ownership-based in textbook semaphore useUsually the owner is expected to unlock it

Students often say “binary semaphore and mutex are exactly the same.” They can solve similar mutual-exclusion problems, but their semantics and ownership rules can differ.

Test-and-set

What Is Test-and-Set?

Test-and-set is an atomic hardware instruction that reads a lock value and changes it in one indivisible operation.

It is not a semaphore operation. Instead, it is a low-level building block that can be used to implement spinlocks or protect short critical sections.

Semaphore

A higher-level synchronization primitive with wait/signal semantics and often scheduler-supported blocking.

Test-and-Set

A hardware atomic instruction commonly used to build a lock.

Semaphore = synchronization primitive · Test-and-set = atomic hardware instruction
Why atomicity matters

Why Must wait() and signal() Be Atomic?

If two processes could change the semaphore value at the same time without protection, the semaphore itself would have a race condition.

The internal update of a semaphore must be performed atomically so two processes cannot corrupt its value or waiting queue.

Operating systems can use hardware atomic operations, interrupt control in limited kernel situations, internal locks or other protected mechanisms to implement semaphore operations safely.

Live learning tool

Semaphore Permit Simulator

This simulator starts with three permits. Use wait() to take a permit and signal() to return one.

Available permits

33 resources available

Event log

Semaphore initialized to 3. Three resource permits are available.

The simulator stops decreasing at zero because there is no permit left to acquire. In a real blocking semaphore, another process would wait until signal() makes permission available again.

Where students usually go wrong

Common Semaphore Mistakes

Forgetting signal()The permit may never be returned, so other processes can remain blocked.
Wrong initial value1 means one permit; 0 often means wait for an event; N can represent N resource units.
Calling wait() in the wrong orderIncorrect ordering can create deadlock.
Calling signal() too earlyThe critical section may become unprotected before shared work is finished.
Confusing semaphore with shared integerA semaphore is a synchronization object whose operations must be atomic.
Confusing test-and-set with semaphoreTest-and-set is a hardware primitive; semaphore is a higher-level synchronization mechanism.
Assuming semaphores prevent all deadlocksWrong semaphore ordering can itself cause deadlock.
Ignoring starvationFairness depends on queue and scheduling policy.
Deadlock warning

Can Semaphores Cause Deadlock?

Yes. Semaphores are tools; incorrect use can create deadlock.

Suppose two processes need semaphores A and B:

P1

wait(A) -> wait(B)

P2

wait(B) -> wait(A)

If P1 holds A while P2 holds B, both can wait forever for the other semaphore.

Semaphore does not automatically prevent deadlock; correct resource ordering still matters.
Real OS uses

Where Are Semaphores Used?

Shared buffersCoordinate producers and consumers.
Resource poolsLimit access to N identical resources.
Thread orderingMake one action wait until another action completes.
Kernel synchronizationCoordinate access to shared kernel data where appropriate.
Device accessControl limited device or I/O resources.
Server connection limitsRestrict the number of simultaneous resource users.
Exam shortcut

How to Choose the Initial Semaphore Value

SituationCommon Initial ValueWhy
One critical section permit1Only one process should enter at a time
Three identical resources3Three processes may acquire one resource each
P2 must wait for event from P10P2 blocks until P1 signals
N identical resource unitsNSemaphore count represents free units
Initial value tells you how much permission exists at the beginning.
Exam answer patterns

How to Write Semaphores in Semester Exams

2 marks

Definition

Define semaphore and write the names of wait() and signal().

5 marks

Types + operations

Explain binary and counting semaphores with wait/signal and one resource example.

8-10 marks

Complete answer

Add mutual exclusion, blocking queue, busy waiting, event ordering, test-and-set difference, solved trace and deadlock warning.

Fast memory trick

Wait takes permission · Signal returns permission
Knowledge check

Practice Questions With Answers

1. What is a semaphore in OS?

A semaphore is a synchronization variable used to control access to shared resources and coordinate concurrent processes or threads.

2. What does wait() do?

wait() tries to acquire permission from the semaphore. If permission is unavailable, the process waits according to the semaphore implementation.

3. What does signal() do?

signal() releases permission to the semaphore and may allow a waiting process to continue.

4. What is a binary semaphore?

A binary semaphore represents two logical states and is commonly used for mutual exclusion or simple event synchronization.

5. What is a counting semaphore?

A counting semaphore tracks multiple available units of a resource.

6. Why can a semaphore start at 0?

Starting at 0 is useful when a process must wait until another process signals that an event has occurred.

7. What is test-and-set?

Test-and-set is an atomic hardware instruction used to read and change a lock value in one indivisible operation.

8. Is test-and-set the same as a semaphore?

No. Test-and-set is a low-level atomic instruction, while a semaphore is a higher-level synchronization primitive.

9. Can semaphores cause deadlock?

Yes. Incorrect semaphore ordering or missing signal operations can cause deadlock.

10. What is the difference between mutex and semaphore?

A mutex is mainly an ownership-based mutual-exclusion lock, while a semaphore is a counter/permit synchronization primitive that can also coordinate multiple resources or execution order.

Concept map instead of a normal conclusion

Semaphore Concept Map

SemaphoreSynchronization permission/counter.
wait()Acquire or consume permission.
signal()Release permission or wake a waiter.
Binary semaphoreTwo logical states; often used for exclusion.
Counting semaphoreTracks N available resource units.
Initial value 1One permit for mutual exclusion.
Initial value 0Wait until another process signals an event.
BlockingWaiting process sleeps in a queue.
Busy waitingWaiting process keeps checking.
Test-and-setAtomic hardware instruction used to build locks.
Deadlock riskWrong semaphore order can block processes forever.
Next stepUse semaphores in Producer-Consumer and classical synchronization problems.
Frequently asked questions

Frequently Asked Questions

What is semaphore in OS in simple words?

A semaphore is a synchronization counter or permission mechanism used to control access to shared resources and coordinate processes or threads.

What is the difference between wait() and signal()?

wait() requests or consumes semaphore permission, while signal() releases permission and may allow a waiting process to continue.

What is the difference between binary and counting semaphore?

A binary semaphore represents two logical states, while a counting semaphore tracks multiple available resource units.

Why is semaphore operation atomic?

Semaphore operations must be atomic so concurrent processes cannot corrupt the semaphore value or its waiting queue.

Is test-and-set a semaphore?

No. Test-and-set is an atomic hardware instruction commonly used to build locks, while a semaphore is a higher-level synchronization primitive.

Can semaphore solve process synchronization?

Yes. Semaphores can provide mutual exclusion, control access to multiple resources and enforce execution ordering between processes or threads.

Next practical use

Next Chapter: Producer-Consumer Problem

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources