Open main menu

lensowiki β

Changes

Computer Science/162/proj1

10,210 bytes added, 03:51, 20 February 2023
m
=={{c|KThread.join()}}==
===Implementation===
;New state variables{{c|KThread}} has a new state variable {{c|joinedOnMe}}, a {{c|ThreadQueue}}. , and {{c|isJoined}}, a {{c|boolean}} ;Implementation details
* When {{c|threadA}} calls {{c|threadB.join()}}, {{c|threadB}} adds it to its internal {{c|joinedOnMe}} queue and then puts it to sleep. In {{c|threadB}}'s {{c|finish()}} method, {{c|threadB}} calls {{c|nextThread()}} on its {{c|joinedOnMe}} queue before returning.
* {{c|join()}} also checks that this thread is not equal to the current thread and that {{c|joinedOnMe}} is not already occupied by another thread with a boolean flag, which determines whether {{c|join()}} has already been called on this thread.
===Testing===
* ThreadA {{c|threadA}} prints out a few statements, calls ThreadB{{c|threadB.join()}}, then prints out a few more statements. ThreadB {{c|threadB}} also prints out a series of statements. We want to then verify that ThreadB {{c|threadB}} executes contiguously to completion before ThreadA {{c|threadA}} resumes its execution, as evidenced by the sequence of printed statements. * Have a thread attempt to {{c|join ()}} to itself, and call {{c|join() }} on the same a second thread multiple times, and also attempt to call {{c|join ()}} on a third finished thread(all separately). These should all return immediately because as this is the join condition was not satisfiedexpected behavior.* Have Test a chain of threads. Thread C will attempt to join Thread B. Thread B will attempt to join Thread A. Thread A forks last. Verify that A executes before B, and B executes before C.
===Pseudocode===
{{c|<pre>join() {
Disable interrupts;
If (CurrentThread == self or isJoined) or (status is Finished) {
Re-enable interrupts;
Return; // conditions for join not satisfied
} else {
}
Re-enable interrupts;
}</pre>}}  {{c|<pre>finish(){
// Interrupts have been disabled.
...(existing code)...
Ready the thread in on the joinedOnMe queue;
Sleep (existing);
}</pre>}}
==ConditionCondition2.java==
===Implementation===
;New state variablesCondition2 has a new state variable {{c|waitQueue}}, a {{c|ThreadQueue }} with {{c|transferPriority }} flag set to false.  ;Implementation details* In the {{c|sleep() }} method, we disable interrupts, the calling (current) thread is added to the {{c|waitQueue }} of threads, the corresponding lock is released, and the current thread is put to sleep. When it wakes up, interrupts are re-enabled and the thread attempts to reacquire the condition corresponding lockand interrupts are re-enabled. * The {{c|wake() }} method disables interrupts and checks if retrieves the next thread from {{c|waitQueue is empty}}. If it the thread returned is notnull, the method readies the first that thread in the waitQueueis readied. Finally, wake() the interrupts are re-enables interruptsenabled. * The {{c|wakeAll() }} method also disables the interrupts and stores the next thread from {{c|waitQueue}} as a {{c|KThread}} variable, {{c|nextThread}}. While {{c|nextThread}} is not null, the method will call wake() as long as ready that thread and set {{c|nextThread}} to the next thread from {{c|waitQueue}}. This procedure continues until there are no more threads still in the {{c|waitQueue}}.
===Testing===
* {{c|Condition2.java}} was tested using a class called {{c|CondThread}}, which implements {{c|Runnable}}. The class is instantiated with an integer {{c|iterations}}, a lock, a {{c|Condition2}} variable to call {{c|sleep()}} on, and a {{c|Condition2}} variable to call {{c|wake()}} on. When a {{c|CondThread}} runs, it acquires the lock, then enters a for-loop of 6 iterations. On each iteration, the thread will print out a debug statement noting that the current thread is on the ith iteration. When the loop iteration number is equal to {{c|iterations}}, threads can take one of three actions:*#If the thread's ID is '0', then that thread is the waking thread and calls {{c|wake()}} on its second condition variable.*#If the thread's ID is '0-all', it calls {{c|wakeAll()}} on its second condition variable*#Otherwise, it goes to sleep on its first condition variable. Using the output, we verify that the threads all run in the correct order and all execute to completion.* Sleep several threads on the condition variable. Upon waking, these threads should print a unique statement and perform a {{c|wake() }} on the condition variable. Have one thread perform an initial {{c|wake() }} on the condition variable and verify that all threads are executed.* Sleep several threads on several various condition variables. Verify via console print statements that the proper threads wake up at the correct times according to which condition variable they were sleeping on.* Sleep several threads on the condition variable, then have one final thread wake them all with {{c|wakeAll()}}. Verify that all threads have woken up via console print statements.* Sleep several threads on several various condition variables, then have one thread call {{c|wakeAll()}} on one of the condition variables. Verify via console print statements that all the threads put to sleep on that condition variable wake up and that only those threads wake up.
===Pseudocode===
Sleep{{c|<pre>sleep(){ Disable Interrupts; Add current thread to wait queue; Release the lock; Put the current thread to sleep; Acquire the lock; Re-enable Interrupts;}</pre>}}
{{c|<pre>wake() {
AssertTrue (lock held by current thread);
Disable interrupts;
If there is a thread on the wait queue:
Remove the first thread and wake it;
Re-enable interrupts;
}</pre>}}
Wake(){AssertTrue (lock held by current thread);Disable interrupts;If there is a thread on the wait queue, remove and wake it;Re-enable interrupts; } WakeAll{c|<pre>wakeAll(){ Disable interrupts; While there are threads on the wait queue, call : Remove the first thread and wake().it; Re-enable interrupts; }</pre>}}
=={{c|waitUntil()}}==
===Implementation===
;New state variables
Alarm has a new instance variable, {{c|waitingThreads}}, which is a Java {{c|PriorityQueue}} of waiting threads with the target wake time as their priority. It also contains a new inner class named {{c|WaitingThread}}, which contains a reference to a {{c|KThread}} and its associated {{c|wakeTime}}. The {{c|PriorityQueue waitingThreads}} will be populated with instances of this inner class.
==WaitUntil()=====;Implementation===Alarm has a new instance variable, waitingThreads, which is a Java PriorityQueue of waiting threads with the target wake time as their priority. It also contains a new inner class named waitingThread, which contains a reference to the KThread and its associated wakeTime.details* {{c|waitUntil() }} creates a new instance of {{c|waitingThread}}, which will associate the currentThread current thread with the give given time argument. It will then add this {{c|waitingThread }} instance to the {{c|PriorityQueue }} and put the current thread to sleep. This method is atomic. * {{c|timerInterrupt() peek }} peeks at the first {{c|WaitingThread }} in the {{c|waitQueue }} and check checks if its associated wake time is less than or equal to the current time. If it is, this method will pop the {{c|WaitingThread }} off the {{c|waitQueue }} and wake the associated thread. This process is repeated until the wake time of the first {{c|WaitingThread }} is greater than the current time.
===Testing===
* Have several threads execute for loops that print out a series of statements. Check that statements for different threads are all printed contiguously and in ordering consistent with their respective wake times. * Have a main thread the timer interrupt print out system times with a set frequencydebug statement, and have timed threads print the times they go to sleep and when they have exceeded their wait timeswoken up. Verify that they execute wake up relatively close to their expected exit wake time. * Make sure threads called with illegal times return immediately. Test threads that go to sleep chronologically in order (1, 500, 1050) as well as threads that go to sleep with the same times (50, 50) and threads that go to sleep in reverse order (500, 250). Verify they all wake up when they are supposed to.
===Pseudocode===
{{c|<pre>waitUntil(time){
Disable interrupts;
Create a new waitingThread;
Sleep the current thread;
Re-enable interrupts;
}</pre>}}
 {{c|<pre>timerInterrupt(){
AssertTrue (interrupts have already been disabled);
For all waitingThreads that have exceeded their associated wait time;
Wake their associated threads and remove from queue;
}</pre>}}
==Communicator==
===Implementation===
We add new ;New state variables {{c|<pre>Lock lock = new Lock(a lock, a bool, two counters, and two condition variables):Lock lockint activeSpeakers = 0int speakerCountwaitingSpeakers = 0int listenerCountactiveListeners = 0bool exInProgressint waitingListeners = 0
Condition speakers
Condition listeners.* We use a Boolean flag which indicates if a transfer is in progress.Condition return</pre>}} ;Implementation details* A The first lone first speaker or listener will be counted as ''active'', or in the process of exchanging a message and returning, and will sleep on its respective the {{c|return}} condition variable until its counterpart wakes it up so that they can both return.* A second thread performing the same action as a counterpart action to the first currently active thread will set the exInProgress flag to truebe counted as ''waiting'', perform its actions and wake the 1st thread; any intruding 3rd thread will not attempt be put to proceed as long as the exInProgress flag is trueвАФthis 3rd thread will sleep on its respective condition variable. Otherwise, so that we can maintain synchronicity.* The 1st thread it will be woken up by the 2nd check if there is an ''active'' thread before of its counterpart action waiting on the 2nd thread returns{{c|return}} condition variable. If there isn't, at which point it will attempt to wake waiting threads of its counterpart action prior to going to sleep on the first return condition variable. If there is a counterpart ''active'' thread , it will set the Boolean wake it up and they both will return. Prior to falsereturning, the counterpart action will also attempt to wake ''waiting '' threads of its type (this is due to the possibility of additional sleeping .* Any interjecting threads being added that execute in between an exchange of message will be stopped by the moment between one thread returning and another about to return)''active'' counters, and finally returnwhich do not decrement until '''both''' counterparts in the exchange have returned.
===Testing===
Our original solution exhibited non-deterministic behavior, so after rewriting it, we decided to stress it exceptionally to make sure that it was working correctly. We tested our communicator in three main ways.
First, we set up a manual sequence of {{c|speak() }} and {{c|listen() }} actions on different threads and executed them in a particular order, verifying that the resulting sequence of messages was correct, monitored via print statements to the console
Second, we set off a random number of speakers, followed by a random number of listeners, and verified that the limiting resource was completely used up, i.e. that a matching number of speakers and listeners returned and that this was equal to the smaller of numbers of created speakers/listeners.
 Finally, we repeated the same procedure, but intermingled the creation of speakers and listeners via {{c|.fork()}}, such that listeners would start listening before all the speakers were queued up.
The latter two tests were run with up to 500 threads of speakers and listeners each (with a temporary override on the number of max threads in Nachos) and the number of listen and speak operations was analyzed via script. The speakers and listeners would print statements while executing code, which allowed us to perform this analysis.
===Pseudocode===speak(word) To be able to perform these tests, we created a number of helper classes which implement Runnable. {{c|MassSpeaker}} and {{ Acquire the lock; While there c|MassListener}} are speakersdesigned to be run by a single thread each. These will iterate until a given limit, and on each iteration, there is a 50% chance that a speak (or an exchange listen) is in progress: Increment the number of speakers and sleep; called. After wakingeach iteration, decrement the number of speakers; Set thread yields to the word opposite thread to speak; Increment number do the same. Debug statements will display what threads are doing at each iteration and how messages are being exchanged. With this we can generate large amounts of speakers; If there are no listeners calls with randomized orders between two threads, and there's no exchange in progress:Go will be able to sleep; If there verify all speaks are listeners and there's no exchange in progress: Wake a listener; else: Wake correctly received by a speaker; Properly set if there is an exchange in progress or not; Release the lock and return;}listen.
listen() A second set of runnables, {{c|MassTSpeaker}} and {{Acquire the lock;While there c|MassTListener}}, are other listeners or an exchange is in progress:Increment the number of listeners and sleep;After wakingdesigned to fork off several threads themselves, decrement the number with each of speakers;Increment the number of listeners;If there these forked threads performing a single speak or listen. These forked threads are no speakers and there's no exhange in progress:Go also executed with 50% chance on each iteration to sleep;If there's no exchange in progress:Wake a speaker;Flip the boolean that indicates provide random ordering. We can also verify if there's an exchange in progress;Set the return value all threads are correctly paired off via print statements to the speaker's word;Decrement the number of listeners;Release the lock and return the word;}console.
===Pseudocode===
{|
| style="vertical-align: top;"|
speak(int word) {
Acquire the lock;
while (There is an active speaker) {
WS++;
Sleep as a waiting speaker;
WS--;
}
AS++;
Set the word;
if (There is an active listener) {
Wake the active listener;
Release the lock;
Return;
} else {
if (There are waiting listeners) {
Wake a waiting listener;
}
Sleep as waiting to return;
AS--;
AL--;
if (There are waiting speakers) {
Wake a waiting speaker;
}
Release the lock;
Return;
}
}
||
listen() {
Acquire the lock;
while (There is an active listener) {
WL++;
Sleep as a waiting listener;
WL--;
}
AL++;
if (There is an active speaker) {
Wake an active speaker;
Store the word;
Release the lock;
Return the word;
} else {
if (There are waiting speakers) {
Wake a waiting speaker;
}
Sleep as waiting to return;
AL--;
AS--;
if (There are waiting listeners) {
Wake a waiting listener;
}
Store the word;
Release the lock;
Return the word;
}
}
|}
==Priority Scheduler==
===Implementation===
;New state variables are shown by the class they appear in: * {{c|PriorityQueue: KThread lastThread.holder}} - this ThreadState: int donatedPriorityPriorityScheduler: TreeSet¬Ђlong (time), KThread¬ї waitQueue* nextThread()* This method retrieves and removes corresponds to the highest priority thread off the Priority-Time set. It calculates this thread's priority based on priorities holder of the threads waiting in resource signified by the queue* {{c|PriorityQueue. It resets the priority waitQueue}} - an ArrayList of thread previously in the lastThread position to its original priorityThreadStates waiting on this resource. The thread to be returned is also set as the new lastThreadUnsorted. * pickNextThread()* This method retrieves the first thread from the Priority{{c|PriorityQueue.dirty}} -Time set without removing it from the set. It creates to true when a new ThreadState from this thread and returns the ThreadState. * getEffectivePriority()* This method sums the associated thread's priority and its donatedPriority. If this sum is less than 7, added to the method returns the sum. Otherwisequeue, the max priority 7 is returned.* setPriority() This method will change the actual priority or any of the thread associated with queues in the ThreadState. The effective priority of lastThread must also be by difference between current threads priority and new prioritywaitQueue flag themselves as dirty. * waitForAccess(priorityQueue) This method puts thread associated with the threadState onto the Priority-Time set{{c|PriorityQueue. The set sorts all threads by priority, then time. The associated thread will then be put to sleep. This method will also recalculate effective priority: it will add up all priorities of }} - the threads in the set and donate it to the lastThread.* acquire()* This method calculates the priority cached highest of the associated thread based on effective priorities of the threads waiting in the queuewaitQueue. It resets the priority of the thread previously in the lastThread position to its original priority. The associated thread This value is invalidated while dirty is set as the new lastThreadtrue.
* {{c|ThreadState.myResources}} - collection of PriorityQueues that signify the Locks or other resources that this thread currently holds.
* {{c|ThreadState.waitingOn}} - collection of PriorityQueues corresponding to resources that this thread has attempted to acquire but could not.
* {{c|ThreadState.effective}} - the cached effective priority of this thread. this value is invalidated when dirty is true
* {{c|ThreadState.dirty}} - set to true when this thread's priority is changed, or when one of the queues in myResources flags itself as dirty.
;Implementation overview
The idea here is that {{c|Thread}}s keep track of the {{c|PriorityQueue}}s corresponding to both the resources that they are currently holding and those that they want to hold. We can do this via hooks in {{c|PriorityQueue}}'s {{c|waitForAccess()}}, {{c|acquire}}, and {{c|nextThread}} methods.
 
Once we have this, every time a thread tries to wait on a queue, or takes control of a queue, we can tell the queue that its overall effective priority may have changed, and it can, in turn, tell the thread that currently holds the resource that one of the {{c|PriorityQueue}}s it holds may have had its priority changed. That holder can in turn tell the same to the {{c|PriorityQueue}}s that it is waiting on, and so forth. Eventually a thread, which is holding a resource that everyone needs, but has a low priority, will be marked for priority recalculation and thus priority escalation.
 
At this point, recalculation is simple. The effective priority of a thread is the maximum of its own actual priority and the priorities of all the {{c|PriorityQueue}}s that it currently holds. The effective priority of a {{c|PriorityQueue}} is the maximum effective priority of all the threads waiting on it (if the queue is supposed to donate priority), and so on and so forth in a mutually recursive manner.
 
;Implementation details
* {{c|PriorityQueue.nextThread()}}
:This method retrieves and removes the highest priority thread off the Priority-Time {{c|ArrayList}}. It then flags the previous holder of this resource as {{c|dirty}}, and removes the queue from that holder's resource list. It then sets the retrieved thread to this queue's new {{c|holder}}, and flags that thread as {{c|dirty}} as well.
* {{c|PriorityQueue.acquire(KThread thread)}}
:Sets the {{c|holder}} of this queue to the specified thread, bypassing the queue. Resets previous {{c|holder}} and sets {{c|dirty}} flags as in {{c|nextThread()}}.
* {{c|PriorityQueue.pickNextThread()}}
:Simply retrieves the highest priority thread off this queue.
* {{c|PriorityQueue.setDirty()}}
:Set this queue's {{c|dirty}} flag, and calls {{c|setDirty}} on the current holder of this thread.
* {{c|PriorityQueue.getEffectivePriority()}}
:If this queue is {{c|dirty}}, returns the maximum of each of the {{c|ThreadState}}s{{c|.getEffectivePriority()}} in this queue. Those calls in turn become mutually recursive when they call {{c|getEffectivePriority()}} on the {{c|PriorityQueues}} in their {{c|myResources}}.
* {{c|ThreadState.setPriority()}}
:This method will change the actual priority of the thread associated with the {{c|ThreadState}}. It then calls {{c|setDirty()}} on this thread.
* {{c|ThreadState.setDirty()}}
:Sets the {{c|dirty}} flag on this thread, then calls {{c|setDirty()}} on each of the {{c|PriorityQueue}}s that the thread is waiting for. Mutually recursive.
* {{c|ThreadState.getEffectivePriority}}
:Like the analogue of this function in {{c|PriorityQueue}}, returns the (cached) priority if this thread is not {{c|dirty}}; otherwise, recalculates by returning the max of the effective priorities of the {{c|PriorityQueue}}s in {{c|myResources}}.
===Testing===
* Instantiate new threads and set their priorities in decreasing order. Have the threads state their priorities as they execute and verify that they were run in decreasing order according to their priorities.
* Verify donation works by creating a high priority thread and joining it to a low priority thread with a high priority thread already queued.
* Create complex set of interdependent threads and multiple locks, verify that execution order is correct.
===Pseudocode===
;PriorityQueue
{{c|<pre>
public void waitForAccess(KThread thread)
add this thread to my waitQueue
thread.waitForAccess(this)
public void acquire(KThread thread)
if I have a holder and I transfer priority, remove myself from the holder's resource list
thread.acquire(this)
public KThread nextThread()
if I have a holder and I transfer priority, remove myself from the holder's resource list
if waitQueue is empty, return null
ThreadState firstThread = pickNextThread();
remove firstThread from waitQueue
firstThread.acquire(this);
return firstThread
 
public int getEffectivePriority()
if I do not transfer priority, return minimum priority
if (dirty)
effective = minimum priority;
for each ThreadState t in waitQueue
effective = MAX(effective, t.getEffectivePriority())
dirty = false;
return effective;
 
public void setDirty()
if I do not transfer priority, there is no need to recurse, return
dirty = true;
if I have a holder, holder.setDirty()
protected ThreadState pickNextThread()
ThreadState ret = null
for each ThreadState ts in waitQueue
if ret is null OR ts has higher priority/time ranking than ret
set ret to ts
return ret;</pre>}}
 
;ThreadState
{{c|<pre>
public int getPriority()
return non-donated priority.
 
public int getEffectivePriority()
if (dirty) {
effective = non-donated priority
for each PriorityQueue pq that I am currently holding
effective = MAX(effective, pq.getEffectivePriority)
}
return effective;
 
public void setPriority(int priority)
set non-donated priority to the argument
setDirty();
public void setDirty()
if already dirty return
dirty = true;
for each of the PriorityQueues pq I am waiting on,
pq.setDirty
 
public void waitForAccess(PriorityQueue waitQueue)
add the waitQueue to my waitingOn list
if the waitQueue was previously in myResources, remove it and set its holder to null.
if waitQueue has a holder, set the queue to dirty to signify possible change in the queue's effective priority
 
public void acquire(PriorityQueue waitQueue)
add waitQueue to myResources list
if waitQueue was in my waitingOn list, remove it
setWaitQueue's holder to me
setDirty();</pre>}}
==Boat.java==
===Implementation===
Algorithm for solving boat problem ;New state variables (high levelall shared):If there are no children on island B or if there are no adults left on island A, two children from island A will pilot over and one will return to A. If there is a child on island B, an adult will pilot over to island B and the child will bring the boat back to island A. Once the adults are all on island A, the children can begin to transfer themselves over to island B. There are the following state variables:{{c|<pre>lock L = new lockLock()boatIsland = Island.A
boatPilot = null
boatDeparting = false
boatLookingForChild = false
numChildrenOnB childCounter = 0numAdultsOnA adultCounterA = 0condition childrenWaitingOnA, adultsWaitingOnA, childrenWaitingOnB, adultsWaitingOnB, waitingToRide, waitingToPilot //separate condition variables all on lock LadultCounterB = 0sleepingChildren = 0waiters = 0
Each thread will attempt to acquire the lock pipe = new Communicator(which represents the boat). If the thread can performs one of its assigned tasks, then it executes it. Otherwise it will go to sleep.</pre>}}
Child Algorithm (with Pseudocode):Each child will begin running Condition variables, all on island A and try to acquire the lock.: {{c|childrenWaitingOnA}}, {{c|adultsWaitingOnA}}, {{c|childrenWaitingOnB}}, {{c|adultsWaitingOnB}}, {{c|waitingToRide}}, {{c|waitingToPilot}}
childItinerary () { myIsland = A while (true) { acquire LIn addition, each thread has a local variable to keep track of which island the person is currently on.
;Implementation overviewIf the child is there are no children on Molokai or if there are no adults left on island A and the boat is available for useOahu, then it two children from Oahu will ask for a passenger child pilot over and go one will return to sleepMolokai. Once If there is a passenger child is foundon Molokai, the pilot an adult will be awoken by the passenger child and pilot them over to island B. He now increments Molokai and the global counter numChildrenOnB. He wakes up child will bring the passenger child so that he can be moved boat back to island B as a passenger and goes to sleepOahu. The passengerThis process, increments carried to completion eventually results in all of the numChildrenOnB counter adults and wakes up the pilotchildren on Molokai. Once the pilot child reawakens, he Each thread will speak attempt to beginacquire the lock (which essentially represents control over the boat), telling . If the begin thread can perform one of the number tasks fitting for the current state of children currently on island B. He then returns to island A and decrements numChildrenOnB. If the number of adults on island A (according to numAdultsOnA) is not 0world, he wakes up the adults waiting on Ait executes it. Otherwise, puts himself it will go to sleep on the children waiting on A condition variable, corresponding to its current role and releases the lock (after wake). Otherwise, he simply releases the locklocation.
if the child is on island A and the boat is not departing { if the boat does not have a pilot and the boat is not looking for a passenger { //first move of pattern boatLookingForChild = true;Implementation details boatPilot = CHILD; sleep and wait to pilot; pilot to B; wake up passenger; increment number of children Each child will begin running on B; boatIsland = B; boatLookingForChild = false; sleep Oahu and wait try to pilot;speakToBegin()decrement num of children on Bchild pilots to A boatIsland = A if number of adults on A != 0 {wake adults waiting on A; sleep and wait on island A; }release L; continue;}acquire the lock.
If the child is on island A Oahu and the boat is asking available for a passengeruse (i.e. {{c|<nowiki>boatLookingForChild == false</nowiki>}} and {{c|<nowiki>boatPilot == null</nowiki>}} and {{c|<nowiki>boatDeparting == false</nowiki>}}), it will assume the child will role of pilot and set the boat as departing{{c|boatLookingForChild}} variable to true, wake up the pilot child, and go then going to sleepon {{c|waitingToPilot}}. After Once a passenger child is found, the pilot child is will be awoken by the passenger child and pilotthem both to Molokai, he will transfer himself while the passenger goes to island B as a passenger and increment numChildrenOnBsleep on {{c|waitingToRide}}. He awakens then increments the {{c|childCounter}}, wakes up the pilot passenger child (so that he can pilot back ride to A with the boat)Molokai, puts the children waiting on B and goes back to sleep, and releases the lock.
else if (boatPilot == CHILD and boatLookingForChild) The passenger, upon arrival at Molokai, increments the {{ boatDeparting = true; wake a pilot; sleep c|childCounter}} and wait speaks to ride; child ride to B; increment {{c|begin()}} the number of children on B; myIsland = B; boatDeparting = false; wake a Molokai. The child passenger then wakes up the pilot; and goes to sleep on island B; release L; continue;{{c|childrenWaitingOnB}}. Once the pilot child reawakens, he returns to Oahu, decrementing {{c|childCounter}}before departure.
If Upon return to Oahu, if the number of adults on Oahu (according to {{c|adultsWaitingOnA}}) is not 0 and there is still a child is left on island B with Molokai to row the boat and back after the boat is not in useadult goes across (according to {{c|childCounter}}), he will the pilot wakes up the adults waiting on A, puts himself back to A sleep on {{c|childrenWaitingOnA}}, releases the lock after wake, and restarts the looop. Otherwise, he simply releases the lock and decrement restarts the counter numChildrenOnBloop.
} else if (myIsland == boatIsland == B The adults all begin on Oahu, try to acquire the lock, and !boatDeparting) each initially increment {decrement num of children on B child pilots to A; myIsland = boatIsland = A; boatPilot = null; release L; continue;{c|adultCounterA}}.
If none of these conditions are metthe adult is on Oahu, the boat is available for use, and there is at least one child is put on Molokai according to {{c|childCounter}}, the adult pilots to Molokai. Otherwise, he wakes a child on {{c|childrenWaitingOnA}} and goes to sleep as waiting on his respective island{{c|adultsWaitingOnA}}.
else If the adult does pilot across, he increments { if {c|adultCounterB}} upon arrival to Molokai, speaks to {{c|begin(myIsland == A)sleep }} the value of {{c|childCounter}}, wakes up a child from {{c|childrenWaitingOnB}} so that he can pilot the boat back to Oahu, and wait then puts himself to ride elsesleep on island B;{{c|adultsWaitingOnB}}. The adult is now done and will never be woken again.
Adult Algorithm (with Pseudocode):The adults all begin If a child is sleeping on Molokai on island A {{c|childrenWaitingOnB}} and gets woken by an adult, he will decrement {{c|childCounter}} and acquire pilot himself back to Oahu. Upon arrival, he releases the lock. The adults also increment a global counter numAdultsOnAand restarts the loop.
adultItineraryFor both adults and children, if the boat is busy or inaccessible as determined by the state of the {{c|boatPilot}}, {{c|boatDeparting}}, {{c|boatLookingForChild}}, and {{c|boatIsland}} variables given the person's current location, each will go back to sleep on the appropriate condition variable () i.e. {{ myIsland = A increment numAdultsOnA while(truec|childrenWaitingOnA}} for child threads on Oahu) { acquire L;.
If ;{{c|begin()}} behavior{{c|begin()}} creates the required number of child and adult is on island A, the boat is available for use threads and the last boat pilot was a child, the adult pilots to island B. He then wakes up one child waiting on island B so that he can pilot the boat back to Aforks them. The adult is now done with its task and goes to sleepThen, thus releasing the lock for other threads it begins to use. if {{c|listen(myIsland == boatIsland == A and !boatDeparting and boatPilot == CHILD and !boatLookingForChild) }} on the one shared Communicator ({ boatPilot = ADULT; adult pilots to B; boatIsland = myIsland = B; wake a child sleeping on B; sleep on B; continue;{c|pipe}Otherwise the adult puts the adults on his respective island to sleep)else When {{ if c|begin(myIsland == A)sleep on A; elsesleep on B;In begin()} receives a message, each time it checks the child threads speaks to it, begin() will check if "spoken" number of children on B is equal to as well as {{c|adultCounterB}} against the number of child spawned threads that it forked. Since all adults must be on B before number of children increases, this tells us that we are doneto see if everyone is across yet.
The reason that it does not check the value of {{c|childCounter}} directly is because by the time it receives the message, it is possible that a child has already piloted back to Oahu, thus decrementing the counter and preventing {{c|begin()}} from knowing the true number of children on Molokai.
===Testing===
Finally, we tested larger numbers of both adults and children and verified that the rowing patterns were correct. We tested both combinations with more adults than children and vice versa. The rowing pattern, as well as number of people on Molokai, was monitored to make sure no rules were being violated.
 
==Design questions==
;Why is it fortunate that we did not ask you to implement priority donation for semaphores?
:Currently, each time a thread acquires a lock or calls {{c|join()}}, we know who is currently holding the resource. This allows us to donate priority to this single resource if a higher-priority thread begins waiting on it. With semaphores, this is not possible for initial values greater than 1, because the last thread to successfully "acquire" the semaphore will not necessarily be the one with the lowest priority. The implementation would need to change to keep track of all threads that are actually using the semaphore currently and thus be able to determine which of those has the lowest priority and needs to "receive" a donation.
;A student proposes to solve the boats problem by use of a counter, AdultsOnOahu. Since this number isn't known initially, it will be started at zero, and incremented by each adult thread before they do anything else. Is this solution likely to work? Why or why not?
:No, because there is no way of enforcing the fact that everyone will increment it before they do anything else.
1,277
edits