2014-11-15 1 views
0

나는 pthread와 세마포어를 사용하여 C에서 잠자는 이발사 문제에 대한 해결책을 구현하려고하는데, 다음과 같이 각 작업을 인쇄해야한다는 요구 사항 중 일부만 있습니다.세마포를 사용하여 잠자는 이발에서 인쇄

  • 이발사가 잠 들어 떨어졌다
  • 고객은 최대
  • 고객이 더 좌석을 사용할 수 없어서
  • 고객은 왼쪽 이발을 기다리고 이발사를 깨우지있다
  • 을 (만 나중에 시간이 임의의 기간을 반환)
  • 고객은 자신의 머리를
  • 고객을 잘라지고 것은 가게

난 단지에서 순서가 인쇄 된 다양한 교착 상태 또는 가진 문을 얻기 위해, 조금이 문제에서 일했습니다 남아있다.

문제에 대한 classical solution은 여기에 완전히 적용되지 않습니다 (예 : "Barber has sleeped sleep", "customer has been barber up up") 또는 인쇄문이 매번 인쇄되기 때문에 컨텍스트 전환 (실제 문제 일 수도 있고 아닐 수도 있음)의 결과로 고장난 것입니다.

내 현재 솔루션, 의사,이 같은 것입니다 :

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) 

그것의 명확한를 내게 이발사가 고객을 적절하게 내 보내지 못한다는 것 - 그러나 심지어 내 구조가 모두 잘못되었다고 느낀다. 내가 문제를 잘못 접근하고 있다고 생각하고 그것을 복잡하게 만들 가능성이 높습니다.

여기에있는 누군가가 현재 솔루션을 구축하는 방법에 대한 제안이나 현재의 구조 조정에 대한 제안 사항이 있으면 크게 환영 할 것입니다. 또는 내가 올바른 방향으로 가고 있다면, 아마도 올바른 방향으로 추진할 것입니다.

감사합니다.

답변

0

나는 그것을 작동시킬 수 있었다.

내가 본 것처럼 보지 못했던 것을 보아도 전에 다른 사람이 나에게 도움을 요청할 경우 내 자신의 질문에 답할 것입니다.

내 원래의 방법은 완전히 꺼지지 않았지만 올바르게 작동하려면 약간의 조정이 필요했습니다. 6 개의 세마포어를 사용하는 대신 읽기/쓰기 액세스를 제어하는 ​​5 : 2와 대기/수면 제어를 사용했습니다.

의사 코드는 다음과 같습니다 : 주에서

# Constants 
SLEEPING = 0 
AWAKE = 1 
BUSY  = 2 

# Read/Write semaphores 
Semaphore rw_chairs = 1  # Access to chairs 
Semaphore rw_status = 1  # Access to barber status 

# Access semaphores 
Semaphore waiting = 0  # Line for waiting customers 
Semaphore cutting = 0  # Semaphore to hold customer while getting hair cut 
Semaphore sleeping = 0  # Semaphore for barber to sleep 

int chairs  = n  # Available chairs to sit in 
int status  = AWAKE # Barber Status (could also be a boolean for sleeping) 
bool finished  = false # Is the program finished 

def Barber(): 
    while not finished: 
     wait(rw_chairs) 
     wait(rw_status) 
     # If there is nobody waiting and the barber isn't asleep 
     if chairs == n and status != SLEEPING: 
     barber = SLEEPING; 
     print("Barber went to sleep!") 
     signal(rw_status) 
     signal(rw_chairs) 
     wait(sleeping) # Go to sleep 
     print("Barber woke up!") 
     signal(waiting) # Let the next customer in 
     else: 
     signal(waiting) # Let the next customer in 
     chairs += 1  # Free the chair they sat in 
     barber = BUSY  # Set the barber to busy 
     signal(rw_status) 
     signal(rw_chairs) 

     # Once it gets here, the barber is awake and must help someone 
     if not finished: 
     print("Barber is cutting a customer's hair") 
     # Cut the customer's hair 
     print("Barber finished cutting the customer's hair") 
     signal(cutting) # Release the customer so they can leave 

    # barber's finally done 
    print("Barber finished work for the day"); 

def Customer(): 
    bool helped = false 

    print("Customer arrived at the Barber Shop!") 
    while not helped: 
     wait(rw_chairs) 
     wait(rw_status) 
     if chairs == n and status == SLEEPING: 
      status = AWAKE 
      print("Customer woke up the barber") 
      signal(rw_status) 
      signal(sleeping) # Wake up the barber 
      wait(waiting)  # Be the next customer to get helped (happens immediately) 
      signal(rw_chairs) 

      helped = true; // This customer is being helped 
     else: 
      signal(rw_status) 
      if chairs > 0: 
      chairs -= 1 # Claim a chair 
      signal(rw_chairs) 
      print("Customer sitting in a chair") 
      wait(waiting) # Wait for the barber 

      helped = true; // This customer is being helped 
      else: 
      print("Barber Shop is busy, will return later") 
      signal(rw_chairs) 
      # Wait a while before returning 
     # If the customer is being helped 
     if helped: 
      print("Customer is getting a hair cut") 
      wait(cutting) 
      print("Customer is finished getting a haircut") 

모든 고객 스레드가 true로 종료 설정, 가입 한 후, 프로그램을 완료합니다 (아마도) 자고 이발사을 깨어.

이 방법을 사용하면 이발사와 고객 모두가 먼저 상태를 읽고, 반대 순서로 해제합니다 (데드락이 순환 대기하는 것을 방지합니다).