Rensselaer Polytechnic Institute CSCI-4210 – Operating Systems David Goldschmidt, Ph.D.
Without synchronization amongst processes (and threads), results are unpredictable how do variables x and y become corrupted?
Processes compete for resources Once obtained, the resource is fully dedicated to a process Often, mutual exclusion is required ▪ No other process is allowed access to the resource Processes cooperate with other processes Shared resources Specific ordering or sequencing of events all of this applies to threads, too!
To synchronize processes (or threads), first identify the critical sections of code If process P i is executing in its critical section, no other process can be executing in their critical sections A critical section guarantees mutual exclusion to one or more resources
The operating system must control access to critical sections and guarantee progress: if no process is executing in its critical section one or more processes wish to enter their critical sections andand andand process selection cannot be postponed indefinitely (starvation) then process selection must be fair and avoid deadlock process selection must be fair and avoid deadlock andand andand
Peterson’s solution is a two-process solution Processes P j and P k share two variables: Variable turn indicates whose turn it is to enter the critical section The flag array specifies if a process is ready to enter its critical section // Process P j while ( true ) { flag[j] = true; // P j ready turn = k; while ( flag[k] && turn == k ) ; // busy wait // CRITICAL SECTION HERE flag[j] = false; } int turn; boolean flag[2];
Model for cooperating processes: A producer process produces information that is consumed by a consumer process ▪ e.g. client-server, transaction processing, etc. Implement using a shared memory segment as a shared buffer Producer adds to the buffer Consumer empties the buffer
also known as the bounded-buffer problem