pythonマルチスレッドノート(4)--駅の切符販売シミュレーション
3470 ワード
import threading
import time
import random
class Worker(threading.Thread):
''' '''
def __init__(self, wait_num=5, index=0):
super().__init__()
self.wait_num = wait_num #
self.setName(' ' + str(index)) #
def run(self):
global counter, mutex
while counter and self.wait_num: #
# ============================
#
# ============================
time.sleep(random.randrange(2,10)) # ,
# ============================
#
# ============================
mutex.acquire() # ①
if counter == 0: # 0
mutex.release() # ③ -----> !!!
print(self.getName(), ': , ')
break
counter = counter - 1 #
print('{}: {} '.format(self.getName(), counter))
mutex.release() # ③
# ============================
#
# ============================
self.wait_num -= 1 #
self.wait_num += random.randrange(0,2) #
if __name__ == '__main__':
#
counter = 20
#
mutex = threading.Lock()
# 4
workers = []
for i in range(4):
wait_num = random.randrange(2,10) #
workers.append(Worker(wait_num, i+1))
#
for w in workers:
w.start()
# / ?
#for w in workers:
# w.join()