CS 372 Operating Systems
Synchronization. Making Water. You need two hydrogen atoms (H), and one oxygen (O) to make water. Write solutions that generate water as soon as the atoms are available. Use monitors.
Here is a code template. MakeH, and MakeO will get called infinitely often, but all methods are called at unpredictable times. make_hydrogen and make_oxygen actually "make" the atoms, and make_water actually "makes" the water molecule. Your code coordinates these processes. The math is correct in this code sample, but there is not enough synchronization code. Please write that code.
public class Water {
private int freeH;
private int freeO;
private static final ReentrantLock lock
= new ReentrantLock();
// You can have additional state if you like
Water() {
freeH = freeO = 0;
}
private void MakeH() {
make_hydrogen();
freeH++;
}
private void MakeO() {
make_oxygen();
freeO++;
}
public void MakeWater() {
make_water();
freeO--
freeH = freeH - 2;
}
}
You need to write three methods: Start(int i, int K), AddMemory(int i, int A) and Terminate(int i). You can assume each process id i is unique. Use an array memory[i] to keep track of the current memory in use by process i. To keep your solution as simple as possible, do not allocate or bounds check it. You can also assume all requests satisfy the constraints above (i.e., your code should not check that the process always requests less than M amount of memory).
public class BankAccounts{
private int accounts;
public class void Account () {
private int total;
public int account_number;
...
Account(...) {
...
}
public void transfer(Account withdraw, Account deposit, int amount) {
synchronized(withdraw) {
synchronized(deposit) {
if(amount > 0) {
withdraw.transaction(-amount);
deposit.transaction(amount);
}
}
}
}
public void transaction(int amount) {
if (amount > 0) total += amount;
else if (total < -amount)
throw new InsufficientFundException()
else total -= amount;
}
}