globalCount++;When the 10 threads exit, globalCount might not be 10. Why?
void Transfer(Account* from, Account* to, int amount) {
from->lock->Acquire();
to->lock->Acquire();
from->balance -= amount;
to->balance += amount;
to->lock->Release();
from->lock->Release();
}
This code can deadlock. What must happen for deadlock to occur? How do
you fix it?Got any?
You should know the following synchronization primitives like the back of your hand:
while(lock is held) block; lock = held;
if(another thread is blocked in Acquire()) unblock other thread; lock = unheld;
while(value == 0) block; value--;
if(another thread is blocked in P()) unblock other thread; value++;
monitorLock->Release(); block; monitorLock->Acquire();
if(another thread is blocked in Wait()) unblock other thread;
for each thread blocked in Wait() unblock other thread;
This class covers several classic synchronization problems
It's very important that you understand how to solve these problems. These problems are considered classic simply because a lot of the synchronization problems you'll run into are variations on these problems. Knowing how to solve these problems will be helpful for homeworks, exams, and life beyond CS120.
Studying solutions to these standard synchronization problems is like studying proofs in CS theory: It is more important to understand the idea behind the solution, instead of memorizing the solution itself. You probably won't get a midterm question that says "Use semaphores to solve bounded buffer." On the other hand, you just might get a midterm question that says "Use semaphores to solve this problem that looks sorta like bounded buffer." Not necessarily bounded buffer of course, but you get the idea.
After the party is seated, they eat for a while, and then they leave, allowing more customers to enter. Clearly, there can never be more than N seated customers at any time, because the restaurant only has N chairs.
Each party of M customers is represented by a thread that executes the following code:
SitDown(M) // eat StandUp(M)
SitDown(M) indicates that a party of size M wants to sit down. A party will start eating as soon as SitDown returns, so SitDown must block until M seats are available. StandUp(M) indicates that a party of size M wants to stand up, freeing M chairs for waiting customers.
Define SitDown and StandUp first using monitors, then using semaphores.
Does your solution guarantee that parties of the same size are served in FIFO order? That is, if a party of 2 arrives, then later another party of 2 arrives, can you guarantee that the first party of 2 will always sit first? If not, how would you enforce this policy?