# 互斥锁同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据,比如 # 一个厕所有3个坑,那么最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去 import threading import time def run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" %n) semaphore.release() if __name__ == '__main__': num = 0 semaphore = threading.BoundedSemaphore(3) #最多允许3个线程同时运行 for i in range(20): t = threading.Thread(target=run,args=[i,]) t.start() while threading.active_count() != 1: print(threading.active_count()) pass else: print("----all threads done----------") print(num)
下面我们来详细的讲解下信号量的例子,先看下测试代码
import threading import time def run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" % n) semaphore.release() if __name__ == '__main__': num = 0 semaphore = threading.BoundedSemaphore(2) # 最多允许3个线程同时运行 for i in range(6): # print(i) t = threading.Thread(target=run, args=[i, ]) t.start() while threading.active_count() != 1: time.sleep(0.5) print(threading.active_count()) else: print("----all threads done----------")
我们会打印出当前active的线程数,这里需要注意,这个线程数还包括我们的主进程,也就是我们这里通过主进程起了6个子线程,那么他的active的线程数为7
我们看下打印的结果
7 run the thread: 1 run the thread: 0 5 5 run the thread: 2 run the thread: 3 3 3 run the thread: 4 run the thread: 5 1 ----all threads done----------
通过上面的结果,我们可以看到active的线程数开始为7个,因为我们一共有7个线程,只要线程被start了,该线程就是active状态的
然后线程数从7个变为5个,在变为3个,在变为1个,最后为0个,这样我们就可以清晰的看到,同时只有2个线程可以在运行
我们下面把信号量调整为3个
import threading import time def run(n): semaphore.acquire() time.sleep(1) print("run the thread: %s" % n) semaphore.release() if __name__ == '__main__': num = 0 semaphore = threading.BoundedSemaphore(3) # 最多允许3个线程同时运行 for i in range(6): # print(i) t = threading.Thread(target=run, args=[i, ]) t.start() while threading.active_count() != 1: time.sleep(0.5) print(threading.active_count()) else: print("----all threads done----------")
结果如下
7 run the thread: 1 run the thread: 0 run the thread: 2 4 4 run the thread: 5 run the thread: 3 run the thread: 4 1 ----all threads done----------
最后我们不设置信号量
测试代码如下
import threading import time def run(n): # semaphore.acquire() time.sleep(1) print("run the thread: %s" % n) # semaphore.release() if __name__ == '__main__': num = 0 semaphore = threading.BoundedSemaphore(3) # 最多允许3个线程同时运行 for i in range(6): # print(i) t = threading.Thread(target=run, args=[i, ]) t.start() while threading.active_count() != 1: time.sleep(0.5) print(threading.active_count()) else: print("----all threads done----------")
结果如下
7 run the thread: 0 run the thread: 2 run the thread: 3 run the thread: 5 run the thread: 1 run the thread: 4 1 ----all threads done----------
现在应该小伙伴们对python多线程的信号量应该掌握了把
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/20882.html