# 互斥锁同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据,比如# 一个厕所有3个坑,那么最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去import threadingimport timedef run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" %n) semaphore.release()if __name__ == '__main__': num = 0 semaphore = threading.BoundedSemaphore(3) #最多允许3个线程同时运行 for i in range(20): t = threading.Thread(target=run,args=[i,]) t.start()while threading.active_count() != 1: print(threading.active_count()) passelse: print("----all threads done----------") print(num)