SlideShare a Scribd company logo
1 of 44
Copyright ©: University of Illinois CS 241 Staff 1
Synchronization and
Semaphores
Discussion
 In uni-processors
 Concurrent processes cannot be overlapped, only interleaved
 A process runs until it invokes a system call, or is interrupted
 To guarantee mutual exclusion, hardware support could help
by allowing the disabling of interrupts
While(true) {
/* disable interrupts */
/* critical section */
/* enable interrupts */
/* remainder */
}
 What’s the problem with this solution?
2Copyright ©: University of Illinois CS 241 Staff
Discussion
 In multi-processors
 Several processors share memory
 Processors behave independently in a peer relationship
 Interrupt disabling will not work
 We need hardware support where access to a memory
location excludes any other access to that same location
 The hardware support is based on execution of multiple
instructions atomically (test and set)
3Copyright ©: University of Illinois CS 241 Staff
Test and Set Instruction
boolean Test_And_Set(boolean* lock)
atomic {
boolean initial;
initial = *lock;
*lock = true;
return initial;
}
Note: this is more accurate
than the textbook version
atomic = executed in a single shot
without any interruption
4Copyright ©: University of Illinois CS 241 Staff
Using Test_And_Set for
Mutual Exclusion
Pi {
while(1) {
while(Test_And_Set(lock)) {
/* spin */
}
/* Critical Section */
lock =0;
/* remainder */
}
}
void main () {
lock = 0;
parbegin(P1,…,Pn);
}
5
What's the problem?
Copyright ©: University of Illinois CS 241 Staff
Using Test_And_Set for
Mutual Exclusion
Pi {
while(1) {
while(Test_And_Set(lock)) {
/* spin */
}
/* Critical Section */
lock =0;
/* remainder */
}
}
void main () {
lock = 0;
parbegin(P1,…,Pn);
}
Works, but has performance loss because of busy waiting.
6Copyright ©: University of Illinois CS 241 Staff
Semaphores
 Fundamental Principle:
 Two or more processes want to
cooperate by means of simple signals
 Special Variable: semaphore s
 A special kind of “int” variable
 Can’t just modify or set or increment or
decrement it
7Copyright ©: University of Illinois CS 241 Staff
Semaphores
 Before entering critical section
 semWait(s)
 Receive signal via semaphore s
 “down” on the semaphore
 Also: P – proberen
 After finishing critical section
 semSignal(s)
 Transmit signal via semaphore s
 “up” on the semaphore
 Also: V – verhogen
 Implementation requirements
 semSignal and semWait must be atomic
8Copyright ©: University of Illinois CS 241 Staff
Semaphores vs. Test_and_Set
Semaphore
semaphore s = 1;
Pi {
while(1) {
semWait(s);
/* Critical Section */
semSignal(s);
/* remainder */
}
}
Test_and_Set
lock = 0;
Pi {
while(1) {
while(Test_And_Set(lock));
/* Critical Section */
lock =0;
/* remainder */
}
}
9Copyright ©: University of Illinois CS 241 Staff
 Avoid busy waiting by suspending
 Block if s == False
 Wakeup on signal (s = True)
Inside a Semaphore
 Requirement
 No two processes can execute wait() and signal()
on the same semaphore at the same time!
 Critical section
 wait() and signal() code
 Now have busy waiting in critical section implementation
+ Implementation code is short
+ Little busy waiting if critical section rarely occupied
− Bad for applications may spend lots of time in critical sections
Copyright ©: University of Illinois CS 241 Staff 10
Inside a Semaphore
 Add a waiting queue
 Multiple process
waiting on s
 Wakeup one of the
blocked processes
upon getting a signal
 Semaphore data structure
typedef struct {
int count;
queueType queue;
/* queue for procs.
waiting on s */
} SEMAPHORE;
11Copyright ©: University of Illinois CS 241 Staff
Binary Semaphores
typedef struct bsemaphore {
enum {0,1} value;
queueType queue;
} BSEMAPHORE;
void semSignalB (bsemaphore s)
{
if (s.queue is empty())
s.value = 1;
else {
remove P from s.queue;
place P on ready list;
}
}
void semWaitB(bsemaphore s) {
if (s.value == 1)
s.value = 0;
else {
place P in s.queue;
block P;
}
}
12Copyright ©: University of Illinois CS 241 Staff
General Semaphore
typedef struct {
int count;
queueType queue;
} SEMAPHORE;
void semSignal(semaphore s) {
s.count++;
if (s.count ≤ 0) {
remove P from s.queue;
place P on ready list;
}
}
void semWait(semaphore s) {
s.count--;
if (s.count < 0) {
place P in s.queue;
block P;
}
}
13Copyright ©: University of Illinois CS 241 Staff
void semWait(semaphore s) {
s.count--;
if (s.count < 0) {
place P in s.queue;
block P;
}
}
Making the operations atomic
 Isn’t this exactly what semaphores were trying to
solve? Are we stuck?!
 Solution: resort to test-and-set
14
typedef struct {
boolean lock;
int count;
queueType queue;
} SEMAPHORE;
void semWait(semaphore s) {
while (test_and_set(lock)) { }
s.count--;
if (s.count < 0) {
place P in s.queue;
block P;
}
lock = 0;
}
Copyright ©: University of Illinois CS 241 Staff
Making the operations atomic
 Busy-waiting again!
 Then how are
semaphores better
than just using
test_and_set?
15
void semWait(semaphore s) {
while (test_and_set(lock)) { }
s.count--;
if (s.count < 0) {
place P in s.queue;
block P;
}
lock = 0;
}
 T&S: busy-wait during critical section
 Sem.: busy-wait just during semWait, semSignal:
very short operations!
Copyright ©: University of Illinois CS 241 Staff
Mutual Exclusion Using
Semaphores
semaphore s = 1;
Pi {
while(1) {
semWait(s);
/* Critical Section */
semSignal(s);
/* remainder */
}
}
16Copyright ©: University of Illinois CS 241 Staff
Value of
Semaphore
lock
Queue A
semWait(lock)
0
1
semWait(lock)
B
-1
semSignal(lock)
0
semSignal(lock)
1
Process Process Critical Region
Normal Execution
Blocked on
semaphore
lock
B
17Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 1
semaphore s = 2;
Pi {
while(1) {
semWait(s);
/* CS */
semSignal(s);
/* remainder */
}
}
 What happens?
 When might this be
desirable?
18Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 1
semaphore s = 2;
Pi {
while(1) {
semWait(s);
/* CS */
semSignal(s);
/* remainder */
}
}
 What happens?
 When might this be
desirable?
19Copyright ©: University of Illinois CS 241 Staff
s = 2 1× 0× -1×
Semaphore Example 1
semaphore s = 2;
Pi {
while(1) {
semWait(s);
/* CS */
semSignal(s);
/* remainder */
}
}
 What happens?
 Allows up to 2
processes to enter CS
 When might this be
desirable?
 Need up to 2
processes inside CS
 e.g., limit number of
processes reading a var
 Be careful not to violate
mutual exclusion
inside CS!
20Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 2
semaphore s = 0;
Pi {
while(1) {
semWait(s);
/* CS */
semSignal(s);
/* remainder */
}
}
 What happens?
 When might this be
desirable?
21Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 2
semaphore s = 0;
Pi {
while(1) {
semWait(s);
/* CS */
semSignal(s);
/* remainder */
}
}
 What happens?
 When might this be
desirable?
22Copyright ©: University of Illinois CS 241 Staff
s = 0 -1× -2× -3×
Semaphore Example 2
semaphore s = 0;
Pi {
while(1) {
semWait(s);
/* CS */
semSignal(s);
/* remainder */
}
}
 What happens?
 No one can enter CS!
Ever!
 When might this be
desirable?
 Never!
23Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 3
semaphore s = 0;
P1 {
/* do some stuff */
semWait(s);
/* do some more stuff */
}
semaphore s; /* shared */
P2 {
/* do some stuff */
semSignal(s);
/* do some more stuff */
}
 What happens?
 When might this be desirable?
24Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 3
semaphore s = 0;
P1 {
/* do some stuff */
semWait(s);
/* do some more stuff */
}
semaphore s; /* shared */
P2 {
/* do some stuff */
semSignal(s);
/* do some more stuff */
}
 What happens?
 When might this be desirable?
25Copyright ©: University of Illinois CS 241 Staff
s = 1 0× 1×
Semaphore Example 3
semaphore s = 0;
P1 {
/* do some stuff */
semWait(s);
/* do some more stuff */
}
semaphore s; /* shared */
P2 {
/* do some stuff */
semSignal(s);
/* do some more stuff */
}
 What happens?
 P1 waits until P2 signals
 if P2 signals first, P1 does not wait
 When might this be desirable?
 Having a process/thread wait for another process/thread
26Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 4
Process 1 executes:
while(1) {
semWait(S);
a;
semSignal(Q);
}
Process 2 executes:
while(1) {
semWait(Q);
b;
semSignal(S);
}
 Two processes
 Two semaphores: S and Q
 Protect two critical variables ‘a’ and ‘b’.
 What happens in the pseudocode if Semaphores S and
Q are initialized to 1 (or 0)?
27Copyright ©: University of Illinois CS 241 Staff
Semaphore Example 4
Process 1 executes:
while(1) {
semWait(S);
a;
semSignal(Q);
}
Process 2 executes:
while(1) {
semWait(Q);
b;
semSignal(S);
}
28Copyright ©: University of Illinois CS 241 Staff
S = 0
Q = 0
-1×
-1×
Semaphore Example 4
Process 1 executes:
while(1) {
semWait(S);
a;
semSignal(Q);
}
Process 2 executes:
while(1) {
semWait(Q);
b;
semSignal(S);
}
29Copyright ©: University of Illinois CS 241 Staff
S = 1
Q = 1
0×
0×
1×
1×
0×
0×
Semaphore Example 4
Process 1 executes:
while(1) {
semWait(S);
a;
semSignal(Q);
}
Process 2 executes:
while(1) {
semWait(Q);
b;
semSignal(S);
}
30Copyright ©: University of Illinois CS 241 Staff
S = 1
Q = 1
0×
0×
-1×
1×
0×
0×
1×
Be careful!
Copyright ©: University of Illinois CS 241 Staff 31
semSignal(s);
critical_section();
semWait(s);
critical_section();
semSignal(s);
semWait(s);
critical_section();
semWait(s);
critical_section();
semWait(s);
semWait(s);
semWait(s);
critical_section();
semSignal(s);
semSignal(s);
1
2
3
4
5
Deadlock or Violation of Mutual Exclusion?
Be careful!
Copyright ©: University of Illinois CS 241 Staff 32
semSignal(s);
critical_section();
semWait(s);
critical_section();
semSignal(s);
semWait(s);
critical_section();
semWait(s);
critical_section();
semWait(s);
Mutual exclusion violation
Mutual exclusion violation
Possible deadlock
Certain deadlock!
semWait(s);
semWait(s);
critical_section();
semSignal(s);
semSignal(s);
Deadlock again!
1
2
3
4
5
POSIX Semaphores
 Named Semaphores
 Provides synchronization between unrelated process and
related process as well as between threads
 Kernel persistence
 System-wide and limited in number
 Uses sem_open
 Unnamed Semaphores
 Provides synchronization between threads and between
related processes
 Thread-shared or process-shared
 Uses sem_init
33Copyright ©: University of Illinois CS 241 Staff
POSIX Semaphores
 Data type
 Semaphore is a variable of type sem_t
 Include <semaphore.h>
 Atomic Operations
int sem_init(sem_t *sem, int pshared,
unsigned value);
int sem_destroy(sem_t *sem);
int sem_post(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_wait(sem_t *sem);
34Copyright ©: University of Illinois CS 241 Staff
Unnamed Semaphores
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned
value);
 Initialize an unnamed semaphore
 Returns
 0 on success
 -1 on failure, sets errno
 Parameters
 sem:
 Target semaphore
 pshared:
 0: only threads of the creating process can use the semaphore
 Non-0: other processes can use the semaphore
 value:
 Initial value of the semaphore
You cannot make a copy of a
semaphore variable!!!
35Copyright ©: University of Illinois CS 241 Staff
Sharing Semaphores
 Sharing semaphores between threads
within a process is easy, use pshared==0
 Forking a process creates copies of any
semaphore it has… sem_t semaphores are not
shared across processes
 A non-zero pshared allows any process
that can access the semaphore to use it
 Places the semaphore in the global (OS)
environment
36Copyright ©: University of Illinois CS 241 Staff
sem_init can fail
 On failure
 sem_init returns -1 and sets errno
sem_t semA;
if (sem_init(&semA, 0, 1) == -1)
perror(“Failed to initialize semaphore semA”);
Value > sem_value_max
Resources exhausted
Insufficient privileges
EINVAL
ENOSPC
EPERM
causeerrno
37Copyright ©: University of Illinois CS 241 Staff
Semaphore Operations
#include <semaphore.h>
int sem_destroy(sem_t *sem);
 Destroy an semaphore
 Returns
 0 on success
 -1 on failure, sets errno
 Parameters
 sem:
 Target semaphore
 Notes
 Can destroy a sem_t only once
 Destroying a destroyed semaphore gives undefined results
 Destroying a semaphore on which a thread is blocked gives undefined
results
38Copyright ©: University of Illinois CS 241 Staff
Semaphore Operations
#include <semaphore.h>
int sem_post(sem_t *sem);
 Unlock a semaphore
 Returns
 0 on success
 -1 on failure, sets errno (== EINVAL if semaphore doesn’t exist)
 Parameters
 sem:
 Target semaphore
 sem > 0: no threads were blocked on this semaphore, the semaphore
value is incremented
 sem == 0: one blocked thread will be allowed to run
 Notes
 sem_post() is reentrant with respect to signals and may be invoked from
a signal-catching function
39Copyright ©: University of Illinois CS 241 Staff
Semaphore Operations
#include <semaphore.h>
int sem_wait(sem_t *sem);
 Lock a semaphore
 Blocks if semaphore value is zero
 Returns
 0 on success
 -1 on failure, sets errno (== EINTR if interrupted by a signal)
 Parameters
 sem:
 Target semaphore
 sem > 0: thread acquires lock
 sem == 0: thread blocks
40Copyright ©: University of Illinois CS 241 Staff
Semaphore Operations
#include <semaphore.h>
int sem_trywait(sem_t *sem);
 Test a semaphore’s current condition
 Does not block
 Returns
 0 on success
 -1 on failure, sets errno (== AGAIN if semaphore already locked)
 Parameters
 sem:
 Target semaphore
 sem > 0: thread acquires lock
 sem == 0: thread returns
41Copyright ©: University of Illinois CS 241 Staff
Example: bank balance
 Want shared variable
balance to be protected
by semaphore when used
in:
 decshared – a function
that decrements the
current value of balance
 incshared – a function
that increments the
balance variable.
Copyright ©: University of Illinois CS 241 Staff 42
Example: bank balance
int decshared() {
while (sem_wait(&balance_sem) == -1)
if (errno != EINTR)
return -1;
balance--;
return sem_post(&balance_sem);
}
int incshared() {
while (sem_wait(&balance_sem) == -1)
if (errno != EINTR)
return -1;
balance++;
return sem_post(&balance_sem);
} Copyright ©: University of Illinois CS 241 Staff 43
Summary
 Semaphores
 Semaphore implementation
 POSIX Semaphore
 Programming with semaphores
 Next time: solving real problems with
semaphores & more
44Copyright ©: University of Illinois CS 241 Staff

More Related Content

What's hot

Deadlock in Distributed Systems
Deadlock in Distributed SystemsDeadlock in Distributed Systems
Deadlock in Distributed SystemsPritom Saha Akash
 
Operating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphoresOperating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphoresVaibhav Khanna
 
Process management in os
Process management in osProcess management in os
Process management in osMiong Lazaro
 
Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Ra'Fat Al-Msie'deen
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidancewahab13
 
Memory Management in OS
Memory Management in OSMemory Management in OS
Memory Management in OSvampugani
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronizationAli Ahmad
 
Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.Ravi Kumar Patel
 
deadlock handling
deadlock handlingdeadlock handling
deadlock handlingSuraj Kumar
 
Dead Lock in operating system
Dead Lock in operating systemDead Lock in operating system
Dead Lock in operating systemAli Haider
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitorssgpraju
 

What's hot (20)

Deadlock in Distributed Systems
Deadlock in Distributed SystemsDeadlock in Distributed Systems
Deadlock in Distributed Systems
 
Operating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphoresOperating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphores
 
Binary Semaphore
Binary SemaphoreBinary Semaphore
Binary Semaphore
 
Process management in os
Process management in osProcess management in os
Process management in os
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Deadlock Avoidance in Operating System
Deadlock Avoidance in Operating SystemDeadlock Avoidance in Operating System
Deadlock Avoidance in Operating System
 
Deadlock
DeadlockDeadlock
Deadlock
 
Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidance
 
Memory Management in OS
Memory Management in OSMemory Management in OS
Memory Management in OS
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Deadlock ppt
Deadlock ppt Deadlock ppt
Deadlock ppt
 
Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.
 
deadlock handling
deadlock handlingdeadlock handling
deadlock handling
 
Dead Lock in operating system
Dead Lock in operating systemDead Lock in operating system
Dead Lock in operating system
 
Process state in OS
Process state in OSProcess state in OS
Process state in OS
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitors
 
Deadlock Prevention
Deadlock PreventionDeadlock Prevention
Deadlock Prevention
 

Viewers also liked

Lec11 semaphores
Lec11 semaphoresLec11 semaphores
Lec11 semaphoresanandammca
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionBipul Chandra Kar
 
Producer consumer
Producer consumerProducer consumer
Producer consumerMohd Tousif
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationWayne Jones Jnr
 
Producer and consumer classical problem
Producer and consumer classical problemProducer and consumer classical problem
Producer and consumer classical problemlatechwizard
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process SynchronizationSonali Chauhan
 
ITFT_Semaphores and bounded buffer
ITFT_Semaphores and bounded bufferITFT_Semaphores and bounded buffer
ITFT_Semaphores and bounded bufferSneh Prabha
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationEmery Berger
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating SystemRaj Mohan
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating SystemsDr Sandeep Kumar Poonia
 
Advance Operating Systems
Advance Operating SystemsAdvance Operating Systems
Advance Operating SystemsRaghu nath
 

Viewers also liked (20)

Lec11 semaphores
Lec11 semaphoresLec11 semaphores
Lec11 semaphores
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
 
Producer consumer
Producer consumerProducer consumer
Producer consumer
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
 
Producer Consumer
Producer ConsumerProducer Consumer
Producer Consumer
 
Producer and consumer classical problem
Producer and consumer classical problemProducer and consumer classical problem
Producer and consumer classical problem
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 
Producer Consumer Problem
Producer Consumer Problem  Producer Consumer Problem
Producer Consumer Problem
 
6 Synchronisation
6 Synchronisation6 Synchronisation
6 Synchronisation
 
ITFT_Semaphores and bounded buffer
ITFT_Semaphores and bounded bufferITFT_Semaphores and bounded buffer
ITFT_Semaphores and bounded buffer
 
Operating Systems - Advanced Synchronization
Operating Systems - Advanced SynchronizationOperating Systems - Advanced Synchronization
Operating Systems - Advanced Synchronization
 
Paging
PagingPaging
Paging
 
RTOS - Real Time Operating Systems
RTOS - Real Time Operating SystemsRTOS - Real Time Operating Systems
RTOS - Real Time Operating Systems
 
Operating Systems
Operating SystemsOperating Systems
Operating Systems
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating System
 
8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems8. mutual exclusion in Distributed Operating Systems
8. mutual exclusion in Distributed Operating Systems
 
OSCh7
OSCh7OSCh7
OSCh7
 
Advance Operating Systems
Advance Operating SystemsAdvance Operating Systems
Advance Operating Systems
 
Git Atlrug
Git AtlrugGit Atlrug
Git Atlrug
 

Similar to Semaphores OS Basics

16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Verilog Lecture5 hust 2014
Verilog Lecture5 hust 2014Verilog Lecture5 hust 2014
Verilog Lecture5 hust 2014Béo Tú
 
리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3Sangho Park
 
VLSI Lab manual PDF
VLSI Lab manual PDFVLSI Lab manual PDF
VLSI Lab manual PDFUR11EC098
 
Network security mannual (2)
Network security mannual (2)Network security mannual (2)
Network security mannual (2)Vivek Kumar Sinha
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfsagar414433
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfsagar414433
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
dokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdfdokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdfVelmathi Saravanan
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Béo Tú
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerJAX London
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 

Similar to Semaphores OS Basics (20)

14-Semaphores.ppt
14-Semaphores.ppt14-Semaphores.ppt
14-Semaphores.ppt
 
Os4
Os4Os4
Os4
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Verilog Lecture5 hust 2014
Verilog Lecture5 hust 2014Verilog Lecture5 hust 2014
Verilog Lecture5 hust 2014
 
리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3리눅스 드라이버 실습 #3
리눅스 드라이버 실습 #3
 
CH05.pdf
CH05.pdfCH05.pdf
CH05.pdf
 
Lab
LabLab
Lab
 
VLSI Lab manual PDF
VLSI Lab manual PDFVLSI Lab manual PDF
VLSI Lab manual PDF
 
Network security mannual (2)
Network security mannual (2)Network security mannual (2)
Network security mannual (2)
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Verilog Cheat sheet-2 (1).pdf
Verilog Cheat sheet-2 (1).pdfVerilog Cheat sheet-2 (1).pdf
Verilog Cheat sheet-2 (1).pdf
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
 
Verilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdfVerilog_Cheat_sheet_1672542963.pdf
Verilog_Cheat_sheet_1672542963.pdf
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
dokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdfdokumen.tips_verilog-basic-ppt.pdf
dokumen.tips_verilog-basic-ppt.pdf
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
 
verilog ppt .pdf
verilog ppt .pdfverilog ppt .pdf
verilog ppt .pdf
 
Locks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael BarkerLocks? We Don't Need No Stinkin' Locks - Michael Barker
Locks? We Don't Need No Stinkin' Locks - Michael Barker
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
Os3
Os3Os3
Os3
 

Recently uploaded

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 

Recently uploaded (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 

Semaphores OS Basics

  • 1. Copyright ©: University of Illinois CS 241 Staff 1 Synchronization and Semaphores
  • 2. Discussion  In uni-processors  Concurrent processes cannot be overlapped, only interleaved  A process runs until it invokes a system call, or is interrupted  To guarantee mutual exclusion, hardware support could help by allowing the disabling of interrupts While(true) { /* disable interrupts */ /* critical section */ /* enable interrupts */ /* remainder */ }  What’s the problem with this solution? 2Copyright ©: University of Illinois CS 241 Staff
  • 3. Discussion  In multi-processors  Several processors share memory  Processors behave independently in a peer relationship  Interrupt disabling will not work  We need hardware support where access to a memory location excludes any other access to that same location  The hardware support is based on execution of multiple instructions atomically (test and set) 3Copyright ©: University of Illinois CS 241 Staff
  • 4. Test and Set Instruction boolean Test_And_Set(boolean* lock) atomic { boolean initial; initial = *lock; *lock = true; return initial; } Note: this is more accurate than the textbook version atomic = executed in a single shot without any interruption 4Copyright ©: University of Illinois CS 241 Staff
  • 5. Using Test_And_Set for Mutual Exclusion Pi { while(1) { while(Test_And_Set(lock)) { /* spin */ } /* Critical Section */ lock =0; /* remainder */ } } void main () { lock = 0; parbegin(P1,…,Pn); } 5 What's the problem? Copyright ©: University of Illinois CS 241 Staff
  • 6. Using Test_And_Set for Mutual Exclusion Pi { while(1) { while(Test_And_Set(lock)) { /* spin */ } /* Critical Section */ lock =0; /* remainder */ } } void main () { lock = 0; parbegin(P1,…,Pn); } Works, but has performance loss because of busy waiting. 6Copyright ©: University of Illinois CS 241 Staff
  • 7. Semaphores  Fundamental Principle:  Two or more processes want to cooperate by means of simple signals  Special Variable: semaphore s  A special kind of “int” variable  Can’t just modify or set or increment or decrement it 7Copyright ©: University of Illinois CS 241 Staff
  • 8. Semaphores  Before entering critical section  semWait(s)  Receive signal via semaphore s  “down” on the semaphore  Also: P – proberen  After finishing critical section  semSignal(s)  Transmit signal via semaphore s  “up” on the semaphore  Also: V – verhogen  Implementation requirements  semSignal and semWait must be atomic 8Copyright ©: University of Illinois CS 241 Staff
  • 9. Semaphores vs. Test_and_Set Semaphore semaphore s = 1; Pi { while(1) { semWait(s); /* Critical Section */ semSignal(s); /* remainder */ } } Test_and_Set lock = 0; Pi { while(1) { while(Test_And_Set(lock)); /* Critical Section */ lock =0; /* remainder */ } } 9Copyright ©: University of Illinois CS 241 Staff  Avoid busy waiting by suspending  Block if s == False  Wakeup on signal (s = True)
  • 10. Inside a Semaphore  Requirement  No two processes can execute wait() and signal() on the same semaphore at the same time!  Critical section  wait() and signal() code  Now have busy waiting in critical section implementation + Implementation code is short + Little busy waiting if critical section rarely occupied − Bad for applications may spend lots of time in critical sections Copyright ©: University of Illinois CS 241 Staff 10
  • 11. Inside a Semaphore  Add a waiting queue  Multiple process waiting on s  Wakeup one of the blocked processes upon getting a signal  Semaphore data structure typedef struct { int count; queueType queue; /* queue for procs. waiting on s */ } SEMAPHORE; 11Copyright ©: University of Illinois CS 241 Staff
  • 12. Binary Semaphores typedef struct bsemaphore { enum {0,1} value; queueType queue; } BSEMAPHORE; void semSignalB (bsemaphore s) { if (s.queue is empty()) s.value = 1; else { remove P from s.queue; place P on ready list; } } void semWaitB(bsemaphore s) { if (s.value == 1) s.value = 0; else { place P in s.queue; block P; } } 12Copyright ©: University of Illinois CS 241 Staff
  • 13. General Semaphore typedef struct { int count; queueType queue; } SEMAPHORE; void semSignal(semaphore s) { s.count++; if (s.count ≤ 0) { remove P from s.queue; place P on ready list; } } void semWait(semaphore s) { s.count--; if (s.count < 0) { place P in s.queue; block P; } } 13Copyright ©: University of Illinois CS 241 Staff
  • 14. void semWait(semaphore s) { s.count--; if (s.count < 0) { place P in s.queue; block P; } } Making the operations atomic  Isn’t this exactly what semaphores were trying to solve? Are we stuck?!  Solution: resort to test-and-set 14 typedef struct { boolean lock; int count; queueType queue; } SEMAPHORE; void semWait(semaphore s) { while (test_and_set(lock)) { } s.count--; if (s.count < 0) { place P in s.queue; block P; } lock = 0; } Copyright ©: University of Illinois CS 241 Staff
  • 15. Making the operations atomic  Busy-waiting again!  Then how are semaphores better than just using test_and_set? 15 void semWait(semaphore s) { while (test_and_set(lock)) { } s.count--; if (s.count < 0) { place P in s.queue; block P; } lock = 0; }  T&S: busy-wait during critical section  Sem.: busy-wait just during semWait, semSignal: very short operations! Copyright ©: University of Illinois CS 241 Staff
  • 16. Mutual Exclusion Using Semaphores semaphore s = 1; Pi { while(1) { semWait(s); /* Critical Section */ semSignal(s); /* remainder */ } } 16Copyright ©: University of Illinois CS 241 Staff
  • 17. Value of Semaphore lock Queue A semWait(lock) 0 1 semWait(lock) B -1 semSignal(lock) 0 semSignal(lock) 1 Process Process Critical Region Normal Execution Blocked on semaphore lock B 17Copyright ©: University of Illinois CS 241 Staff
  • 18. Semaphore Example 1 semaphore s = 2; Pi { while(1) { semWait(s); /* CS */ semSignal(s); /* remainder */ } }  What happens?  When might this be desirable? 18Copyright ©: University of Illinois CS 241 Staff
  • 19. Semaphore Example 1 semaphore s = 2; Pi { while(1) { semWait(s); /* CS */ semSignal(s); /* remainder */ } }  What happens?  When might this be desirable? 19Copyright ©: University of Illinois CS 241 Staff s = 2 1× 0× -1×
  • 20. Semaphore Example 1 semaphore s = 2; Pi { while(1) { semWait(s); /* CS */ semSignal(s); /* remainder */ } }  What happens?  Allows up to 2 processes to enter CS  When might this be desirable?  Need up to 2 processes inside CS  e.g., limit number of processes reading a var  Be careful not to violate mutual exclusion inside CS! 20Copyright ©: University of Illinois CS 241 Staff
  • 21. Semaphore Example 2 semaphore s = 0; Pi { while(1) { semWait(s); /* CS */ semSignal(s); /* remainder */ } }  What happens?  When might this be desirable? 21Copyright ©: University of Illinois CS 241 Staff
  • 22. Semaphore Example 2 semaphore s = 0; Pi { while(1) { semWait(s); /* CS */ semSignal(s); /* remainder */ } }  What happens?  When might this be desirable? 22Copyright ©: University of Illinois CS 241 Staff s = 0 -1× -2× -3×
  • 23. Semaphore Example 2 semaphore s = 0; Pi { while(1) { semWait(s); /* CS */ semSignal(s); /* remainder */ } }  What happens?  No one can enter CS! Ever!  When might this be desirable?  Never! 23Copyright ©: University of Illinois CS 241 Staff
  • 24. Semaphore Example 3 semaphore s = 0; P1 { /* do some stuff */ semWait(s); /* do some more stuff */ } semaphore s; /* shared */ P2 { /* do some stuff */ semSignal(s); /* do some more stuff */ }  What happens?  When might this be desirable? 24Copyright ©: University of Illinois CS 241 Staff
  • 25. Semaphore Example 3 semaphore s = 0; P1 { /* do some stuff */ semWait(s); /* do some more stuff */ } semaphore s; /* shared */ P2 { /* do some stuff */ semSignal(s); /* do some more stuff */ }  What happens?  When might this be desirable? 25Copyright ©: University of Illinois CS 241 Staff s = 1 0× 1×
  • 26. Semaphore Example 3 semaphore s = 0; P1 { /* do some stuff */ semWait(s); /* do some more stuff */ } semaphore s; /* shared */ P2 { /* do some stuff */ semSignal(s); /* do some more stuff */ }  What happens?  P1 waits until P2 signals  if P2 signals first, P1 does not wait  When might this be desirable?  Having a process/thread wait for another process/thread 26Copyright ©: University of Illinois CS 241 Staff
  • 27. Semaphore Example 4 Process 1 executes: while(1) { semWait(S); a; semSignal(Q); } Process 2 executes: while(1) { semWait(Q); b; semSignal(S); }  Two processes  Two semaphores: S and Q  Protect two critical variables ‘a’ and ‘b’.  What happens in the pseudocode if Semaphores S and Q are initialized to 1 (or 0)? 27Copyright ©: University of Illinois CS 241 Staff
  • 28. Semaphore Example 4 Process 1 executes: while(1) { semWait(S); a; semSignal(Q); } Process 2 executes: while(1) { semWait(Q); b; semSignal(S); } 28Copyright ©: University of Illinois CS 241 Staff S = 0 Q = 0 -1× -1×
  • 29. Semaphore Example 4 Process 1 executes: while(1) { semWait(S); a; semSignal(Q); } Process 2 executes: while(1) { semWait(Q); b; semSignal(S); } 29Copyright ©: University of Illinois CS 241 Staff S = 1 Q = 1 0× 0× 1× 1× 0× 0×
  • 30. Semaphore Example 4 Process 1 executes: while(1) { semWait(S); a; semSignal(Q); } Process 2 executes: while(1) { semWait(Q); b; semSignal(S); } 30Copyright ©: University of Illinois CS 241 Staff S = 1 Q = 1 0× 0× -1× 1× 0× 0× 1×
  • 31. Be careful! Copyright ©: University of Illinois CS 241 Staff 31 semSignal(s); critical_section(); semWait(s); critical_section(); semSignal(s); semWait(s); critical_section(); semWait(s); critical_section(); semWait(s); semWait(s); semWait(s); critical_section(); semSignal(s); semSignal(s); 1 2 3 4 5 Deadlock or Violation of Mutual Exclusion?
  • 32. Be careful! Copyright ©: University of Illinois CS 241 Staff 32 semSignal(s); critical_section(); semWait(s); critical_section(); semSignal(s); semWait(s); critical_section(); semWait(s); critical_section(); semWait(s); Mutual exclusion violation Mutual exclusion violation Possible deadlock Certain deadlock! semWait(s); semWait(s); critical_section(); semSignal(s); semSignal(s); Deadlock again! 1 2 3 4 5
  • 33. POSIX Semaphores  Named Semaphores  Provides synchronization between unrelated process and related process as well as between threads  Kernel persistence  System-wide and limited in number  Uses sem_open  Unnamed Semaphores  Provides synchronization between threads and between related processes  Thread-shared or process-shared  Uses sem_init 33Copyright ©: University of Illinois CS 241 Staff
  • 34. POSIX Semaphores  Data type  Semaphore is a variable of type sem_t  Include <semaphore.h>  Atomic Operations int sem_init(sem_t *sem, int pshared, unsigned value); int sem_destroy(sem_t *sem); int sem_post(sem_t *sem); int sem_trywait(sem_t *sem); int sem_wait(sem_t *sem); 34Copyright ©: University of Illinois CS 241 Staff
  • 35. Unnamed Semaphores #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned value);  Initialize an unnamed semaphore  Returns  0 on success  -1 on failure, sets errno  Parameters  sem:  Target semaphore  pshared:  0: only threads of the creating process can use the semaphore  Non-0: other processes can use the semaphore  value:  Initial value of the semaphore You cannot make a copy of a semaphore variable!!! 35Copyright ©: University of Illinois CS 241 Staff
  • 36. Sharing Semaphores  Sharing semaphores between threads within a process is easy, use pshared==0  Forking a process creates copies of any semaphore it has… sem_t semaphores are not shared across processes  A non-zero pshared allows any process that can access the semaphore to use it  Places the semaphore in the global (OS) environment 36Copyright ©: University of Illinois CS 241 Staff
  • 37. sem_init can fail  On failure  sem_init returns -1 and sets errno sem_t semA; if (sem_init(&semA, 0, 1) == -1) perror(“Failed to initialize semaphore semA”); Value > sem_value_max Resources exhausted Insufficient privileges EINVAL ENOSPC EPERM causeerrno 37Copyright ©: University of Illinois CS 241 Staff
  • 38. Semaphore Operations #include <semaphore.h> int sem_destroy(sem_t *sem);  Destroy an semaphore  Returns  0 on success  -1 on failure, sets errno  Parameters  sem:  Target semaphore  Notes  Can destroy a sem_t only once  Destroying a destroyed semaphore gives undefined results  Destroying a semaphore on which a thread is blocked gives undefined results 38Copyright ©: University of Illinois CS 241 Staff
  • 39. Semaphore Operations #include <semaphore.h> int sem_post(sem_t *sem);  Unlock a semaphore  Returns  0 on success  -1 on failure, sets errno (== EINVAL if semaphore doesn’t exist)  Parameters  sem:  Target semaphore  sem > 0: no threads were blocked on this semaphore, the semaphore value is incremented  sem == 0: one blocked thread will be allowed to run  Notes  sem_post() is reentrant with respect to signals and may be invoked from a signal-catching function 39Copyright ©: University of Illinois CS 241 Staff
  • 40. Semaphore Operations #include <semaphore.h> int sem_wait(sem_t *sem);  Lock a semaphore  Blocks if semaphore value is zero  Returns  0 on success  -1 on failure, sets errno (== EINTR if interrupted by a signal)  Parameters  sem:  Target semaphore  sem > 0: thread acquires lock  sem == 0: thread blocks 40Copyright ©: University of Illinois CS 241 Staff
  • 41. Semaphore Operations #include <semaphore.h> int sem_trywait(sem_t *sem);  Test a semaphore’s current condition  Does not block  Returns  0 on success  -1 on failure, sets errno (== AGAIN if semaphore already locked)  Parameters  sem:  Target semaphore  sem > 0: thread acquires lock  sem == 0: thread returns 41Copyright ©: University of Illinois CS 241 Staff
  • 42. Example: bank balance  Want shared variable balance to be protected by semaphore when used in:  decshared – a function that decrements the current value of balance  incshared – a function that increments the balance variable. Copyright ©: University of Illinois CS 241 Staff 42
  • 43. Example: bank balance int decshared() { while (sem_wait(&balance_sem) == -1) if (errno != EINTR) return -1; balance--; return sem_post(&balance_sem); } int incshared() { while (sem_wait(&balance_sem) == -1) if (errno != EINTR) return -1; balance++; return sem_post(&balance_sem); } Copyright ©: University of Illinois CS 241 Staff 43
  • 44. Summary  Semaphores  Semaphore implementation  POSIX Semaphore  Programming with semaphores  Next time: solving real problems with semaphores & more 44Copyright ©: University of Illinois CS 241 Staff