Process Synchronization
Process Synchronization
Cooperating Processes
• Independent process cannot affect or be affected by
the execution of another process
• Cooperating process can affect or be affected by the
execution of another process
• Advantages of process cooperation
– Information sharing
– Computation speed-up
– Modularity
– Convenience
Example
• Two Processes P1 & P2
- Sharing Common Variable – Shared
- P1 updates shared as Initial Value
shared = shared + 3 Shared = 4
- P2 updates shared as
shared = shared – 3
Process P1:
1. Load the value of shared in a register of CPU A1.reg1 = shared
A2.reg1 = reg1 + 3
2. Add 3 to the value of the register A3.shared = reg1
3. Load the new value of the register in shared
Process P2:
1. Load the value of shared in a register of CPU B1.reg2 = shared
2. Subtract 3 to the value of the register B2.reg2 = reg2 - 3
B3.shared = reg2
3. Load the new value of the register in shared
Interprocess Synchronization
Cooperating process must synchronize with each other
when they are to use shared resources, such as
- common data structures
- physical devices
Interprocess Synchronization: A set of protocols and
mechanisms used to preserve system integrity and
consistency when concurrent processes share resources
that are serially reusable.
Process states and its operations can be corrupted if
manipulated concurrently and without synchronization.
Need of Interprocess Synchronization
while (true) {
/* Produce an item */
while ((( in + 1) % BUFFER SIZE) == out)
; /* do nothing -- no free buffers */
buffer[in] = nextProduceditem;
in = (in + 1) % BUFFER SIZE;
}
Bounded Buffer – Consumer Remove() Method
while (true) {
while (in == out)
; // do nothing -- nothing to consume
Must guarantee that no two processes can execute wait () and signal () on the same
semaphore at the same time
Semaphore Implementation with no Busy waiting
• With each semaphore there is an associated waiting
queue.
• Each entry in a waiting queue has two data items:
– value (of type integer)
– pointer to next record in the list
• Two operations:
– block – place the process invoking the operation on the
appropriate waiting queue.
– wakeup – remove one of processes in the waiting
queue and place it in the ready queue.
Classical Problems of Synchronization
• Bounded-Buffer Problem
• Readers and Writers Problem
• Dining-Philosophers Problem
Bounded-Buffer Problem
Solution of the problem using Semaphores
While (true) {
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think