CS 3340 Windows Programming Test 3: Threading • • • • • • Barbershop Similar to Prog5 (Reader & Writer) Tuesday, April 4 Lab 206 80 minutes Initial solution 2 Barber Shop Customer Queue Barber One Barber with one Customer Queue 3 Before Opening Barber The queue could be empty 4 Barber Shop Opens Barber Barber goes to sleep if the Barber shop opens with an empty queue 5 Before Opening C1 C2 C3 Barber There may be customers waiting in the queue 6 Barber Shop Opens C1 C2 C2 C3 C3 Barber removes customer from the queue Barber C1 Barber wakes up customer after the hair cut 7 Barber Shop is Open C2 C3 C3 Barber C2 C1 8 Barber Shop is Open C3 Barber C3 C2 9 Barber Shop is Open Barber Barber goes to sleep when the queue is empty 10 New Customer Comes when the Barber is Sleeping C4 Customer enters queue, wakes up barber, Then goes to sleep. Barber 11 New Customer Comes when the Barber is Sleeping C4 Barber will remove customer from the queue. Barber C4 12 New Customer Comes C5 C6 Barber C4 13 Barber Shop Closing C5 C6 Barber should finish all waiting customers Barber C4 14 Barber Shop Closing C7 C5 C6 New customers don’t wait when shop is closing Barber C4 15 Barber Shop Closing C8 C6 New customers don’t wait when shop is closing Barber C5 16 Barber Shop Closing C9 New customers don’t wait when shop is closing Barber C6 17 Barber Shop Closed Barber shop can open again Barber 18 Barber Shop Closed C10 C11 New customers wait when shop is closed Barber 19 Barber Shop Opens C11 C11 C10 Barber removes customer from the queue Barber C10 Barber wakes up customer after the hair cut 20 Closing Before Exiting C11 Barber C11 21 Closing Before Exiting Asking user Yes/No Barber 22 User No C1 C2 C3 Customers come and wait Barber 23 Exiting Before Opening C1 C2 C3 Clear customer queue Barber 24 Barber Thread • Creating a new thread when the Barber shop opens • The thread will be terminated when the Shop closed • When the Shop opens again, a new thread is created • The run sub of the Barber class is for one iteration of Open-Close to make code simpler 25 Prog5 ‘ Waits for all readers and writers to finish the work in order to ‘ terminate the program. ‘ Mutual exclusion on the DataObj and the queue must be enforced. Public Shared Sub FinishReadWrite() _database.LockDataObj() Monitor.Enter(FIFOQueue) If FIFOQueue.Count > 0 or _database.TheDatabaseStatus <> DataBaseClass.DatabaseStatus.Empty endProgram.Reset() Else endProgram.Set() End If Then Monitor.Exit(FIFOQueue) _database.ReleaseDataObj() endProgram.WaitOne() End Sub ‘do not know which thread will wake it up 26 JOIN Method Public Sub CloseBarberShop() Monitor.Enter(BarberShopClass.TheBarberStateObj) BarberShopClass.theBarberState = BarberShopClass.BarberState.Closing Monitor.Exit(BarberShopClass.TheBarberStateObj) barberEvent.Set() ‘ Wait until _barberThread is terminated _barberThread.Join() End Sub 27
© Copyright 2026 Paperzz