Sync Problems
Sync Problems
6.1.1
A: Critical Section
a) In my opinion it is not possible for both threads to enter critical section at the
same time.
• In each scenario this is prevented by variable lock, which block current
thread on line 6, so second thread could only unlock current thread
after completing critical section.
• Exist scenario where both threads could execute till line 6:
𝑙𝑜𝑐𝑘[𝑖] = 𝑓𝑎𝑙𝑠𝑒
𝑓𝑙𝑎𝑔[𝑖] = 𝑡𝑟𝑢𝑒
In such scenario both threads will execute their while cycles until
pattern such that:
Then Thread B exit the while loop, but Thread A will still be inside its
own while loop, until Thread B execute critical section and block Thread
B and set its flag to false.
Then threads get to Line 3 with flags equal to true, then both enter the if
condition:
unlock second thread and set own flag to false telling that it doesn’t want to
enter critical section so giving second thread permission to pass while cycle
A:
4: lock[1] = true;
5: flag[0] = false;
B:
4: lock[0] = true;
5: flag[1] = false;
This happens symmetrical for two threads, so it means that both set
corresponding lock to true which means both are unlocked.
Then both enter while cycle and will run it forever because it is not possible to
change lock inside this cycle, which is part of while condition.
A:
while (lock[1] || flag[1])
{
flag[0] = false;
flag[0] = true;
}
A:
while (lock[0] || flag[0])
{
flag[1] = false;
flag[1] = true;
}
So, deadlock arises without rare condition and most likely to appear when
threads are started together.
c) This implementation is quite starvation free, because always after finishing
critical section each thread sets lock and flag to false, so it allows other thread
to exit waiting cycle on Line 6.
A: Thread A is going through while cycle on Lines 6-8 with flag[1] = true and
lock[1] = true.
It appears that Threads B after completing cri=tical section gets to its Line 1
faster than Thread A gets to check it’s while condition on Line 6, then it is
possible for Thread B to go through Line 3 and Line 6 on special State of
flag[0] while Thread A executed Line 7.
Such scheduler scenario is relatively rare and in most cases none of the
threads will starve, still this implementation has chance of starvation with
small probability.
6.1.2
B: Interleaving
It is possible to get 2, here is the scenario:
Step Description
1A Thread A load initial value of x (x = 0) to R1 register
This is only abstract case which shows how it is possible to get 2 at the end, still it is
almost impossible to get with any scheduler.
In such problems Semaphores is used to avoid cases where both Thread enters
critical section at the same time, so they have access to global variable (save x to its
own registers at the same time, so both increment the same value)