#装饰器小技巧一信号量控制 import threading, time NUM = 10 # 定义信号量控制 def synchronized(func): func.__sem__ = threading.Semaphore(value=NUM) print(func.__sem__) def wraper(*args, **kwargs): #支持上下文 with func.__sem__: return func(*args, **kwargs) return wraper #测试函数 @synchronized def test(index): #模拟耗时 print('%d threadId:%d waiting' % (index, threading.current_thread().ident)) time.sleep(2) print('%d threadId:%d leave' % (index, threading.current_thread().ident)) #开启一百线程 for t in range(100): t1 = threading.Thread(target=test, args=(t,)) t1.start() #同样的还支持Lock 互斥锁