Docsity

Understanding Mutex Locks and Semaphores for Concurrency Control - Prof. Jonathan Walpole, Exams of Operating Systems

Partial preview of the text

Download Understanding Mutex Locks and Semaphores for Concurrency Control - Prof. Jonathan Walpole and more Exams Operating Systems in PDF only on Docsity!

CS 333

Introduction to Operating Systems Class 4 – Synchronization Primitives

Semaphores^ Jonathan Walpole^ Computer Science Portland State University

An Example using a Mutex^ 1 repeat^2

Lock(myLock); 3 critical section 4 Unlock(myLock); 5 remainder section 6 until FALSE

1 repeat 2 Lock(myLock); 3 critical section 4 Unlock(myLock); 5 remainder section 6 until FALSE

Shared data:

Mutex myLock;

Test-and-set-lock instruction (TSL, tset)^ ‰^ A lock is a single word variable with two values^ ™

0 = FALSE = not locked ™ 1 = TRUE = locked

‰^ Test-and-set does the following

atomically

:

™^ Get the (old) value ™^ Set the lock to TRUE ™^ Return the old value^ If

the returned value was FALSE...^ Then

you got the lock!!!

If^ the returned value was TRUE...

Then

someone else has the lock(so try again later)

Test and set lock

FALSE^ Lock

Test and set lock^ P

Lock FALSE

FALSE = Lock Available!!

Test and set lock

TRUE

FALSE

Lock

P

Test and set lock

TRUE^ Lock

P^

P^

P

P

TRUE

TRUE

TRUETRUE

TRUETRUE

Test and set lock

TRUE^ Lock

P^

P^

P

P

TRUE

TRUE

TRUETRUE

TRUETRUE

Test and set lock

FALSE^ Lock

P^

P^

P

P

TRUE

TRUE

TRUETRUE

TRUETRUE

Test and set lock

FALSE^ Lock

P^

P^

P

P

TRUE

FALSE

Test and set lock

TRUE^ Lock

P^

P^

P

P

TRUETRUE

TRUETRUE

Critical section entry code with TSL^ 1 repeat^2 while(TSL(lock))^3

no-op; 4 critical section 5 Lock = FALSE; 6 remainder section7 until FALSE

1 repeat 2 while(TSL(lock)) 3

no-op; 4 critical section 5 Lock = FALSE; 6 remainder section7 until FALSE

J

I

‰^ Guarantees that only one thread at a time willenter its critical section ‰^ Note that processes are busy while waiting^ ™

Spin locks

Synchronization primitives^ ‰^ Sleep^ ™

Put a thread to sleep ™ Thread becomes BLOCKED

‰^ Wakeup^ ™

Move a BLOCKED thread back onto “Ready List” ™ Thread becomes READY (or RUNNING)

‰^ Yield^ ™

Move to another thread ™ Does not BLOCK thread ™ Just gives up the current time-slice

But how can these be implemented?^ ‰^ In User Programs:^ ™

System calls to the kernel

‰^ In Kernel:^ ™

Calls to the thread scheduler routines