标签:start format nbsp form run while target 信号 线程锁
线程锁(也称互斥锁)是同一时间只允许一个线程在执行,信号量可以用来表示同一时间允许执行的线程的数目。
import threading import time def run(n): semaphore.acquire() time.sleep(1) print ‘run the thread: {}\n‘.format(n) semaphore.release() if __name__ == ‘__main__‘: semaphore = threading.BoundedSemaphore(5) for i in range(22): t = threading.Thread(target=run, args=(i,)) t.start() while threading.active_count() != 1: pass else: print ‘---all threads done---‘
结果可以看到是五个五个的一起执行
run the thread: 0
run the thread: 3
run the thread: 4
run the thread: 2
run the thread: 1
run the thread: 5
run the thread: 8
run the thread: 9
run the thread: 7
run the thread: 6
run the thread: 10
run the thread: 14
run the thread: 13
run the thread: 11
run the thread: 12
...
标签:start format nbsp form run while target 信号 线程锁
原文地址:https://www.cnblogs.com/allenzhang-920/p/10201048.html