python(Semaphore(信号量)threading 5个线程同时运行)

# Author:Sooele
import threading, time
def run(n):
   semaphore.acquire()  #信号量获取一把锁
   time.sleep(1)
   print("run the thread: %s\n" % n)
   semaphore.release()
if __name__ == '__main__':
   num = 0
   semaphore = threading.BoundedSemaphore(5)  # 最多允许5个线程同时运行
   for i in range(20):
      t = threading.Thread(target=run, args=(i,))
      t.start()
while threading.active_count() != 1:
   pass  # print threading.active_count()
else:
   print('----all threads done---')
   print(num)

说点什么

avatar
  Subscribe  
提醒