Unit 1 CH 3
Unit 1 CH 3
Process Synchronization
register1 = counter
register1 = register1 + 1
counter = register1
• counter-- could be implemented as
register2 = counter
register2 = register2 - 1
counter = register2
do {
critical section
turn = j;
remainder section
} while (true);
do {
flag[i] = true;
turn = j;
while (flag[j] && turn = = j);
critical section
flag[i] = false;
remainder section
} while (true);
do {
acquire lock
critical section
release lock
remainder section
} while (TRUE);
Definition:
boolean test_and_set (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}
1.Executed atomically
2.Returns the original value of passed parameter
3.Set the new value of passed parameter to “TRUE”.
if (*value == expected)
*value = new_value;
return temp;
}
1.Executed atomically
2.Returns the original value of passed parameter “value”
3.Set the variable “value” the value of the passed parameter
“new_value” but only if “value” ==“expected”. That is, the swap takes
place only under this condition.
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}
do {
...
/* produce an item in next_produced */
...
wait(empty);
wait(mutex);
...
/* add next produced to the buffer */
...
signal(mutex);
signal(full);
} while (true);
Do {
wait(full);
wait(mutex);
...
/* remove an item from buffer to next_consumed */
...
signal(mutex);
signal(empty);
...
/* consume the item in next consumed */
...
} while (true);
do {
wait(rw_mutex);
...
/* writing is performed */
...
signal(rw_mutex);
} while (true);
// eat
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
} while (TRUE);
• What is the problem with this algorithm?
• Deadlock handling
• Allow at most 4 philosophers to be sitting simultaneously at
the table.
• Allow a philosopher to pick up the forks only if both are
available (picking must be done in a critical section.
• Use an asymmetric solution -- an odd-numbered
philosopher picks up first the left chopstick and then the
right chopstick. Even-numbered philosopher picks up first
the right chopstick and then the left chopstick.
monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }
initialization_code() {
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
}
DiningPhilosophers.pickup(i);
EAT
DiningPhilosophers.putdown(i);
wait(mutex);
…
body of F;
…
if (next_count > 0)
signal(next)
else
signal(mutex);
• Mutual exclusion within a monitor is ensured
x_count++;
if (next_count > 0)
signal(next);
else
signal(mutex);
wait(x_sem);
x_count--;
Department of Computer Science and Engineering (AI)
Monitor Implementation (Cont.)
if (x_count > 0) {
next_count++;
signal(x_sem);
wait(next);
next_count--;
}
R.acquire(t);
...
access the resurce;
...
R.release;
• OpenMP
void update()
{
/* read/write memory */
}