Public Calamity 공화국에서 상자가있는 상자 (여기에는 상자가 화장실이있는 상자)가있는 것으로 가정합니다. Republic의 규칙에 따르면 욕실은 남성과 여성 모두 사용할 수 있지만 동시에는 사용할 수 없다고합니다. 이 WC의 사용을 제어하는 동시 모니터 기반 알고리즘을 작성하십시오.Python의 분산 및 병렬 컴퓨터 Unisex 욕실 솔루션
화장실에 들어가는 절차는 욕실에서 수행됩니다. 성공적으로 화장실에 들어간 후, 사람들은 procedureBoxBox를 호출하여 상자를 사용해야합니다. 모든 상자가 사용 중이면 대기열에서 기다려야합니다. 욕실에 충분한 공간이 있어야합니다. 상자를 사용한 후 각 사용자는 liberaBox 프로 시저를 호출하여 다른 사람들이 사용할 수있게합니다.
공화국은 여전히 화장실 사용이 다음과 같이 공정해야한다고 주장합니다. 한 지점에서 화장실이 동성 (일부 사용 상자와 다른 사람들이 대기), 그리고 이성의 첫 번째 사람이 사용하고 있다고 가정 도착, 그래서 P. 라고 : P는 후에 화장실을 입력 •
욕실에서 모든 x 개인의 출구;
• P가 예상하는 한, 다른 동성 개인이 도착하면 P와 동시에 화장실을 사용합니다.
• P가 기다리는 동안, 이성애자가 화장실을 사용하게되면 P (그리고 동성 친구가있는 경우)가 화장실에서 나간다.
• P (와 동성 친구)가 화장실을 사용하는 동안 P와 같은 섹스를하는 경우 화장실을 사용하기 전에 P의 이성애자가 모두 퇴사 할 것으로 예상됩니다.
각 남녀는 각각 별도의 절차를 거쳐야합니다. 욕실에 대한 접근을 통제하는 사람은 없지만 모든 사람들은 욕실 사용 규칙을 알고 그 규칙에 순종합니다 (아무도 그 방침을 지키지 않습니다!).
세 가지 문제를 해결해야합니다
문제 1 : 화장실이 단 하나의 상자를 가지고 고려 (N = 1). 모두 50 명이 성 (성 확률이 같음)을 설정하는 난수 생성기가있는 욕실을 사용합니다. 도착하는 사람들 사이의 시간이 1 ~ 7 초 있도록
는 난수 생성기를 사용합니다. ~각 사람은 정확히 5 초 동안 화장실을 사용합니다. 동기화를 위해 스레드와 모니터를 사용하십시오. 공유 메모리를 사용할 수도 있습니다. 프로그램 끝에서 다음을 포함하는 보고서를 실행하십시오.
• 각 성별 인원수;
• 각 성별로 화장실을 사용하는 평균 대기 시간.
상자 사용률 (사용 시간/총 시간).
문제 2 : 욕실에 3 개의 상자 (n = 3)가 있고 총 인원이 150 인 것으로 간주하십시오.
문제 3 : 화장실 5 상자를 가지고 지금 생각해 (N = 5)과 사람의 총 수는 250
import threading
import random
from time import sleep
# constants
MALE = 1
FEMALE = 0
print("\n***************************************************************\nBem vindo ao banheiro unisex da Rep. Calamidade Pública\n***************************************************************\n\nDigite 1 para Problema 1\nDigite 2 para Problema 2\nDigite 3 para Problema 3\n\n***************************************************************")
print("")
menu = input("Seleção: ")
# global variables
queue = list() # to maintain queue outside bathroom
countPerson = 1 # provides id for each person
countMale = 0
countFemale = 0
PeopleInBathroom = 0
GenderUsingBathroom = 0
if menu == '1':
numBox = 1
elif menu == '2':
numBox = 3
elif menu == '3':
numBox = 5
# semaphores
sem_bathroom = threading.Semaphore(value=numBox)
sem_queue = threading.Semaphore()
sem_mutex = threading.Semaphore()
#generates people who need to use bathroom at random times
def GeneratePeople():
global queue
global countMale
global countFemale
global countPerson
if menu == '1':
sem_queue.acquire()
for i in range(0, 50):
if random.randint(0,1) == MALE:
queue.insert(0,[MALE,countPerson]);
countPerson += 1
countMale += 1
print ("Um homem chegou na fila na posição #", countPerson-1)
sleep(random.randint(1, 7))
else:
queue.insert(0,[FEMALE,countPerson]);
countPerson += 1
countFemale += 1
print ("Uma mulher chegou na fila na posição #", countPerson-1)
sleep(random.randint(1, 7))
sem_queue.release()
elif menu == '2':
sem_queue.acquire()
for i in range(0, 150):
if random.randint(0,1) == MALE:
queue.insert(0,[MALE,countPerson]);
countPerson += 1
countMale += 1
print ("Um homem chegou na fila na posição #", countPerson-1)
sleep(random.randint(1, 7))
else:
queue.insert(0,[FEMALE,countPerson]);
countPerson += 1
countFemale += 1
print ("Uma mulher chegou na fila na posição #", countPerson-1)
sleep(random.randint(1, 7))
sem_queue.release()
elif menu == '3':
sem_queue.acquire()
for i in range(0, 250):
if random.randint(0,1) == MALE:
queue.insert(0,[MALE,countPerson]);
countPerson += 1
countMale += 1
print ("Um homem chegou na fila na posição #", countPerson-1)
sleep(random.randint(1, 7))
else:
queue.insert(0,[FEMALE,countPerson]);
countPerson += 1
countFemale += 1
print ("Uma mulher chegou na fila na posição #", countPerson-1)
sleep(random.randint(1, 7))
sem_queue.release()
# end of GeneratePeople
# function to send people into bathroom for queue
def entraBanheiro():
global queue
global GenderUsingBathroom
global PeopleInBathroom
while 1:
sem_queue.acquire()
if len(queue)>0:
p = queue.pop()
sem_queue.release()
sem_mutex.acquire() # for GenderUsingBathroom
if GenderUsingBathroom == p[0] : # if same gender, go in
sem_mutex.release()
sem_bathroom.acquire()
t = threading.Thread(target=liberaBox,args=(p,))
t.start()
else: # if different gender, wait till all others come out
print ("Esperando por outra pessoa do mesmo sexo")
while PeopleInBathroom > 0:
sem_mutex.release()
sleep(1)
sem_mutex.acquire()
sem_mutex.release()
sem_bathroom.acquire()
GenderUsingBathroom = p[0]
t1 = threading.Thread(target=liberaBox,args=(p,))
t1.start()
else:
sem_queue.release()
# end of entraBanheiro
def liberaBox(person): # monitors the usage of bathroom for each person
global PeopleInBathroom
flag = 1
sem_mutex.acquire()
if person[0] == FEMALE:
print("Uma mulher acabou de entrar no banheiro")
flag = 0
else:
print ("Um homem acabou de entrar no banheiro")
PeopleInBathroom += 1 # enters bathroom
sem_mutex.release()
sleep(5) # spend some time in bathroom
sem_mutex.acquire()
PeopleInBathroom -= 1 #leave bathroom
print ("Pessoa #" , person[1]," acabou de sair do banheiro")
sem_mutex.release()
sem_bathroom.release()
# end of liberaBox
if __name__ == "__main__":
t1 = threading.Thread(target=GeneratePeople)
t1.start()
t2 = threading.Thread(target=entraBanheiro)
t2.start()
#print("\n***************************************************************\nEstatisticas\n\n***************************************************************\n")
#print("Homens: ", countMale)
#print("Mulheres: ", countFemale)
문제는 코드들이에 입력 먼저 모든 사람을 생성입니다입니다 화장실. 동시에 두 스레드 실행을 위해 이것을 구현하는 방법은 무엇입니까?
스레딩 대신 다중 처리를 사용하십시오. 파이썬의 쓰레드는 실제로 평행하지 않습니다. 다음을 살펴보십시오. https://stackoverflow.com/questions/1697571/python-threading-appears-to-run-threads-sequentially 찾고 계신 것이 있습니다 : https://stackoverflow.com/questions/ 2046603/threading-or-writing-a-se없이 sub-function-in-a-subprocess가 가능합니다. – epinal
프로세스가 어떻게 구현 되나요? – MatheusVieira
https://stackoverflow.com/a/2046630/4585081 대기열을 다중 처리 대기열로 변경했는지 확인하십시오. Join을 호출하기 전에 2 개의 프로세스를 스팸시킵니다. – epinal