python 多线程信号量semaphore

import threading
import logging
import time


def worker(s):
  logging.debug('starting')
  with s:
      name = threading.current_thread().name
      print(name)
      time.sleep(2)


logging.basicConfig(
  level=logging.DEBUG,
  format='%(asctime)s (%(threadName)-2s) %(message)s',
)

s = threading.Semaphore(5)

for i in range(100):
  t = threading.Thread(
      target=worker,
      name=str(i),
      args=(s,),
  )
  t.start()

你可能感兴趣的:(python 多线程信号量semaphore)