Con Currency
Con Currency
Con Currency
procedure Pn () {}
Initialization code ( .) { }
}
}
Schematic ,iew of a %onitor
Condition .ariables
condition x, y;
Two operations on a condition variable:
x.wait () a process that invokes the operation is
suspended.
x.signal () resumes one of processes (if any) that
invoked x.wait ()
%onitor with Condition .ariables
Solution to +ining Philoso#hers
monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];
void pickup (int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING) self [i].wait;
}
void putdown (int i) {
state[i] = THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
void test (int i) {
if ( (state[(i + 4) % 5] != EATING) &&
(state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING) ) {
state[i] = EATING ;
self[i].signal () ;
}
}
initialization_code() {
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
}
Each philosopher I invokes the operations pickup()
and putdown() in the following sequence:
DiningPhilosophters.pickup (i);
EAT
DiningPhilosophers.putdown (i);
%onitor "m#lementation Using Sema#hores
.ariables
semaphore mutex; // (initially = 1)
semaphore next; // (initially = 0)
int next-count = 0;nEach procedure F
will be replaced by
wait(mutex);
body of F;
if (next_count > 0)
signal(next)
elses
ignal(mutex);nMutual exclusion
within a monitor is ensured.
%onitor "m#lementation
For each condition variable x, we have:
semaphore x_sem; // (initially = 0)
int x-count = 0;nThe operation x.wait can
be implemented as:
x-count++;
if (next_count > 0)
signal(next);
else
signal(mutex);
wait(x_sem);
x-count--;
The operation x.signal can be implemented as:
if (x-count > 0) {
next_count++;
signal(x_sem);
wait(next);
next_count--;
}
A %onitor to Allocate Single Resource
monitor ResourceAllocator
{
boolean busy;
condition x;
void acquire(int time) {
if (busy)
x.wait(time);
busy = TRUE;
}
void release() {
busy = FALSE;
x.signal();
}
initialization code() {
busy = FALSE;
}
}
Synchronization &'am#les
Solaris
Windows XP
Linux
Pthreads
Solaris Synchronization
"m#lements a ,ariety of locs to su##ort multitasking,
multithreading (including real-time threads), and
multiprocessing
Uses adaptive mutexes for efciency when protecting data
from short code segments
Uses condition variables and readers-writers locks when
longer sections of code need access to data
Uses turnstiles to order the list of threads waiting to acquire
either an adaptive mutex or reader-writer lock
-indows /P Synchronization
Uses interrupt masks to protect access to global resources
on uniprocessor systems
Uses spinlocks on multiprocessor systems
Also provides dispatcher objects which may act as either
mutexes and semaphores
Dispatcher objects may also provide events
An event acts much like a condition variable
Linu' Synchronization
Linux:lPrior to kernel Version 2.6, disables interrupts to
implement short critical sections
Version 2.6 and later, fully preemptive
Linux provides:
semaphores
spin locks
Pthreads Synchronization
Pthreads API is OS-independent
It provides:
mutex locks
condition variablesnNon-portable extensions include:
read-write locks
spin locks
Atomic !ransactions
System Model
Log-based Recovery
Checkpoints
Concurrent Atomic Transactions
System %odel
Assures that operations happen as a single logical unit of
work, in its entirety, or not at all
Related to feld of database systems
Challenge is assuring atomicity despite computer system
failures
Transaction - collection of instructions or operations that
performs single logical function
Here we are concerned with changes to stable storage
disk
Transaction is series of read and write operations
Terminated by commit (transaction successful) or abort
(transaction failed) operation Aborted transaction must be
rolled back to undo any changes it performed
!y#es of Storage %edia
Volatile storage information stored here does not survive
system crashes
Example: main memory, cache
Nonvolatile storage Information usually survives crashes
Example: disk and tape
Stable storage Information never lost
Not actually possible, so approximated via replication or
RAID to devices with independent failure modes
Goal is to assure transaction atomicity where failures
cause loss of information on volatile storage
Log-$ased Reco,ery
Record to stable storage information about all modifcations
by a transaction
Most common is write-ahead logging
Log on stable storage, each log record describes single
transaction write operation, including
Transaction name
Data item name
Old value
New value
<Ti starts> written to log when transaction Ti starts
<Ti commits> written when Ti commits
Log entry must reach stable storage before operation
on data occurs
Log-$ased Reco,ery Algorithm
Using the log0 system can handle any ,olatile memory errors
Undo(Ti) restores value of all data updated by Ti
Redo(Ti) sets values of all data in transaction Ti to new
values
Undo(Ti) and redo(Ti) must be idempotent
Multiple executions must have the same result as one
execution
If system fails, restore state of all updated data via log
If log contains <Ti starts> without <Ti commits>, undo(Ti)
If log contains <Ti starts> and <Ti commits>, redo(Ti)
Chec#oints
Log could become long, and recovery could take long
Checkpoints shorten log and recovery time.
Checkpoint scheme:
1.Output all log records currently in volatile storage to stable
storage
2.Output all modifed data from volatile to stable storage
3.Output a log record <checkpoint> to the log on stable storage
Now recovery only includes Ti, such that Ti started executing
before the most recent checkpoint, and all transactions after Ti
All other transactions already on stable storage
Concurrent !ransactions
Must be equivalent to serial execution serializability
Could perform all transactions in critical section
Inefcient, too restrictive
Concurrency-control algorithms provide serializability
Serializability
Consider two data items A and B
Consider Transactions T0 and T1
Execute T0, T1 atomically
Execution sequence called schedule
Atomically executed transaction order called serial
schedule
For N transactions, there are N! valid serial schedules
Schedule 12 !3 then !1
4onserial Schedule
Nonserial schedule allows overlapped execute
Resulting execution not necessarily incorrect
Consider schedule S, operations Oi, Oj
Confict if access same data item, with at least one write
If Oi, Oj consecutive and operations of diferent
transactions & Oi and Oj dont confict
Then S with swapped order Oj Oi equivalent to S
If S can become S via swapping nonconficting operations
S is confict serializable
Schedule 52 Concurrent Serializable Schedule
Locing Protocol
Ensure serializability by associating lock with each data
item
Follow locking protocol for access control
Locks
Shared Ti has shared-mode lock (S) on item Q, Ti can
read Q but not write Q
Exclusive Ti has exclusive-mode lock (X) on Q, Ti can
read and write Q
Require every transaction on item Q acquire appropriate
lock
If lock already held, new request may have to wait
Similar to readers-writers algorithm
!wo-#hase Locing Protocol
Generally ensures confict serializability
Each transaction issues lock and unlock requests in two
phases
Growing obtaining locks
Shrinking releasing locks
Does not prevent deadlock
!imestam#-based Protocols
Select order among transactions in advance timestampordering
Transaction Ti associated with timestamp TS(Ti) before Ti
starts
TS(Ti) < TS(Tj) if Ti entered system before Tj
TS can be generated from system clock or as logical
counter incremented at each entry of transaction
Timestamps determine serializability order
If TS(Ti) < TS(Tj), system must ensure produced schedule
equivalent to serial schedule where Ti appears before Tj
!imestam#-based Protocol "m#lementation
Data item Q gets two timestamps
W-timestamp(Q) largest timestamp of any transaction
that executed write(Q) successfully
R-timestamp(Q) largest timestamp of successful read(Q)
Updated whenever read(Q) or write(Q) executed
Timestamp-ordering protocol assures any conficting read
and write executed in timestamp order
Suppose Ti executes read(Q)
If TS(Ti) < W-timestamp(Q), Ti needs to read value of Q
that was already overwritten
read operation rejected and Ti rolled back
If TS(Ti) W-timestamp(Q)
read executed, R-timestamp(Q) set to max(Rtimestamp(
Q), TS(Ti))
!imestam#-ordering Protocol
Supose Ti executes write(Q)
If TS(Ti) < R-timestamp(Q), value Q produced by Ti was needed
previously and Ti assumed it would never be produced
Write operation rejected, Ti rolled back
If TS(Ti) < W-tiimestamp(Q), Ti attempting to write obsolete value
of Q
Write operation rejected and Ti rolled back
Otherwise, write executed
Any rolled back transaction Ti is assigned new timestamp and
restarted
Algorithm ensures confict serializability and freedom from
deadlock
Schedule Possible Under !imestam# Protocol