You are on page 1of 2

do {

flag[i] = TRUE;
turn = j;
while (flag[j] && turn == j);
// critical section
flag[i] = FALSE;
// remainder section
} while (TRUE);
Abdullah Rehman

F2021266327

Peterson algorithm

flag[i] = TRUE: This line indicates that Process 1 is interested in entering the
critical section. It sets its flag to true, indicating its intention to enter the critical
section.

turn = j: Process 1 sets the turn variable to the other process's index (j), indicating
that it's the other process's turn to enter the critical section.

while (flag[j] && turn == j): This is the busy-wait loop. Process 1 waits until the
other process's flag is false (flag[j] == FALSE) or it's Process 1's turn (turn == j).

Critical Section: The code inside the critical section is where the actual work is
done that needs to be protected from concurrent access by other processes.

flag[i] = FALSE: Process 1 resets its flag to false, indicating that it has completed
its critical section.

Remainder Section: The code after the critical section is the remainder section,
which contains non-critical code that can be executed concurrently by other
processes.

} while (TRUE): The entire block is enclosed in an infinite loop, ensuring that
Process 1 repeats this process indefinitely
do {
flag[j] = TRUE;
turn = i;
while (flag[i] && turn == i);
// critical section
flag[j] = FALSE;
// remainder section

} while (TRUE);

flag[j] = TRUE: Process 2 sets its flag to true, indicating its intention to enter the
critical section.

turn = i: Process 2 sets the turn variable to the other process's index (i), indicating
that it's the other process's turn to enter the critical section.

while (flag[i] && turn == i): Process 2 waits until the other process's flag is false
(flag[i] == FALSE) or it's Process 2's turn (turn == i).

Critical Section: The code inside the critical section is where the actual work is
done that needs to be protected from concurrent access by other processes.

flag[j] = FALSE: Process 2 resets its flag to false, indicating that it has completed
its critical section.

Remainder Section: The code after the critical section is the remainder section,
which contains non-critical code that can be executed concurrently by other
processes.

} while (TRUE): The entire block is enclosed in an infinite loop, ensuring that
Process 2 repeats this process indefinitely.

You might also like