Semphore,是一种带计数的线程同步机制,当调用release时,增加计算,当acquire时,减少计数,当计数为0时,自动阻塞,等待release被调用
代码:
1 import threading 2 import time 3 4 sempaphore = threading.Semaphore(3) #计数为1 5 6 def fun(): 7 print "Thread %s is waiting semphore\n" % threading.currentThread().getName() 8 sempaphore.acquire() 9 print "Thread %s get semphore\n" % threading.currentThread().getName() 10 time.sleep(1) 11 print "Thread %s release semphore\n" % threading.currentThread().getName() 12 sempaphore.release() 13 14 15 if __name__ == "__main__": 16 t1 = threading.Thread(target=fun) 17 t2 = threading.Thread(target=fun) 18 t3 = threading.Thread(target=fun) 19 t4 = threading.Thread(target=fun) 20 21 t1.start() 22 t2.start() 23 t3.start() 24 t4.start() 25 26 t1.join() 27 t2.join() 28 t3.join() 29 t4.join()