风-fmgao

导航

信号量

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/18


from threading import Thread,Semaphore,currentThread
import time
import random
sm = Semaphore(3)


def task():
    # sm.acquire()
    # print('%s in ' % currentThread().getName())
    # sm.release()

    # 等价于以上代码
    with sm:
        print('%s in ' % currentThread().getName())
        time.sleep(random.randint(1, 3))


if __name__ == '__main__':
    for i in range(10):
        t = Thread(target=task)
        t.start()



posted on 2018-06-18 23:17  风-fmgao  阅读(86)  评论(0编辑  收藏  举报