from multiprocessing import Process
import random
import time
from multiprocessing import Semaphore
def ktv(i,sem):
sem.acquire() #获取钥匙
print('%s走进ktv'%i)
time.sleep(random.randint(1,5))
print('%s走出ktv'%i)
sem.release() #还钥匙
if __name__ == '__main__':
sem = Semaphore(4) #定义同一时间允许进入房间的人数
for i in range(20):
p = Process(target=ktv, args=(i,sem)) #传入信号量参数
p.start()
原文:https://www.cnblogs.com/konglinqingfeng/p/9688525.html