hw2-s24

.pdf

School

University of California, Riverside *

*We aren’t endorsed by this school

Course

153

Subject

Computer Science

Date

May 24, 2024

Type

pdf

Pages

6

Uploaded by MagistrateNarwhal4033

Report
Homework 2 for CS153 (Spring 2024) Due: 5/6/2024 Instructions: Problem 1: (3 points) Write code, including clear synchronization logic, to simulate a set of dominos (number is N) that have to fall in order. Each domino is a thread that has a local variable i that indicates its number.
Problem 2 (6 points) A local laundromat with 3 washing machines is implementing synchronization between customers using semaphores. Each customer first allocates a machine (the machine number is returned by allocate(), and when they are done returns the machine using release. Available is an array keeping track of whether each of the 3 machines is available (which is represented as 1; 0 is unavailable). 1. int allocate() /* Finds and allocates a free washing machine. */ 2. { 3. int i; //i is not shared 4. nfree.wait(); 5. for (i=0; i < 3; i++) 6. if (available [i] != 0 { 7. available[i] = 0; 8. return i; 9. } 10. } 11. 12. release(int machine) /* Release machine */ 13. { 14. available[machine] = 1; 15. nfree.signal(); 16. } (a) (2 points) What is the purpose of nfree? What should it be intialized to? (b) (4 points) Unfortunately, sometimes two customers were getting assigned the same machine, and a fight followed. Explain by tracking two threads representing the customers that fought, exactly how they got assigned the same machine.
Problem 3 (8 points). You are writing code for the voting machines for an upcoming election. You use shared counters, one for each candidate to keep track of the votes as they come from the different voting machines. You can think of each machine as a thread: every time it receives a vote, it increments a counter for that candidate. (a) (2 point) Explain what could go wrong with this implementation if we do not use synchronization (b) (2 points) Use Semaphores to solve this problem without changing the logic of the code other than adding the semaphore operations. You can show pseudo code or describe you changes clearly. Are there different alternatives as to where to place the semaphores?
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help