3.2.3 信号

Semaphore(信号量)

互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如学校门口的小旅馆有5间房,那最多只允许5对小情侣进去啪,后面的人只能等里面有人出来了才能再进去。

示例

import threading, time

def run(n):
    semaphore.acquire()    #信号量获取,一次5个
    time.sleep(1)    #啪1秒
    print("run the thread: %s\n" % n)
    semaphore.release()    #啪完,退房


if __name__ == '__main__':

    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---')

运行结果

run the thread: 1
run the thread: 3
run the thread: 2
run the thread: 0
run the thread: 4

run the thread: 6
run the thread: 5
run the thread: 8
run the thread: 7
run the thread: 9

run the thread: 10
run the thread: 11
run the thread: 13
run the thread: 14
run the thread: 12

run the thread: 15
run the thread: 16
run the thread: 18
run the thread: 17
run the thread: 19

----all threads done---

运行结果需要动态展示才能看出来,效果就是上面20条信息是分4次,每次5个刷出来的。

你可能感兴趣的:(3.2.3 信号)