我試圖在C中使用pthread和信號量來實現睡眠理髮師問題的解決方案,只有部分要求是每個動作都必須在發生時打印出來,例如:使用信號量在睡眠理髮師中打印
- 理髮睡着
- 客戶已意識到理髮了
- 客戶正在等待理髮
- 客戶離開是因爲沒有座位是可用的(後來才返回的隨機時間段)
- 客戶得到他的頭髮剪
- 客戶已經離開了商店
我在這個問題一點點在努力,只拿到打印出來的無序各種死鎖或有聲明。
該問題的classical solution在這裏並不完全適用,因爲這會導致每次打印報表(例如「理髮師睡着了」,然後是「客戶已經喚醒了理髮師」),或者它會打印報表由於上下文切換(這可能是或者可能不是真正的問題)而導致無序。
我目前的解決方案,在僞代碼,是這樣的:
int chairs = N # available chairs
bool is_sleeping = false
bool is_cutting = false
bool finished = false # All customers taken care of (Changed in main)
# Semaphores for read/write access
semaphore rw_chairs = 1
semaphore rw_sleeping = 1
semaphore rw_cutting = 1
semaphore barber_ready = 0 # Barber ready to cut hair
semaphore sleeping = 0 # Barber is sleeping
semaphore cutting = 0 # Barber cutting a customer's hair
def Barber():
while not finished:
wait(rw_chairs)
wait(rw_sleeping)
# If no chairs are being used
if chairs == N:
is_sleeping = true
print("Barber is sleeping!")
signal(rw_chairs) # Allow others to read/write
signal(rw_sleeping)
wait(sleeping) # Wait for customer to wake him up
signal(barber_ready) # Allow customers into the chair
print("Barber woke up!")
else:
signal(rw_signal)
chairs += 1
signal(barber_ready)
signal(rw_chairs)
# If the barber isn't done for the day, help the customer
if not finished:
print("Helping a customer")
# Wait a random amount of time
print("Finished helping a customer")
signal(cutting) # Let the customer leave after the hair cut
else:
print("Barber is done for the day!")
def Customer():
bool helped = false
while not helped:
wait(rw_chairs)
wait(rw_cutting)
if chairs == N and not is_cutting: # If the barber is free
wait(rw_sleeping)
if is_sleeping:
signal(sleeping) # Wake the barber up
is_sleeping = false
print("Customer has woken the barber up")
signal(rw_sleeping)
is_cutting = true
signal(rw_chairs)
signal(rw_cutting)
wait(barber_ready) # Wait for the barber to be ready
wait(cutting) # Wait for him to finish cutting hair
print("Customer has had his hair cut")
helped = true
else if chairs > 0:
chairs -= 1
print("Customer is waiting in a chair")
signal(rw_chairs)
signal(rw_cutting)
wait(barber_ready)
wait(cutting)
print("Customer has had his hair cut")
helped = true
else:
signal(rw_chairs)
signal(rw_office)
print("All chairs taken, will return later")
# Wait a random amount of time
print("Customer is leaving the barbershop")
當這個沒有得到一個僵局,使用3張椅子,我得到以下輸出:
Barber has fallen asleep
Customer is waiting in a chair
Customer is waiting in a chair
Customer is waiting in a chair
All chairs used, will return later
All chairs used, will return later
... (repeat the above line infinitely)
其清晰對我來說,理髮師沒有正確地讓顧客進來 - 但即使如此,我覺得我的結構是完全錯誤的。我認爲我正在處理錯誤的問題,並且可能會使問題過於複雜化。
如果有人對我如何構建工作解決方案有什麼建議,或者對重組我的現有解決方案提出建議,那將不勝感激。或者如果我走在正確的軌道上,可能會朝着正確的方向前進。
謝謝!