day9-信号量(Semaphore)
背景
前面介绍了互斥锁的作用是同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据
信号量
说明:
import threading,time def run(n): semaphore.acquire() #加锁 time.sleep(1) print("run the thread: %s\n" %n) semaphore.release() #释放锁 if __name__ == '__main__': num= 0 semaphore = threading.BoundedSemaphore(5) #最多允许5个线程同时运行 for i in range(22): t = threading.Thread(target=run,args=(i,)) t.start() while threading.active_count() != 1: pass #print threading.active_count() else: print('----all threads done---') print(num) #运行输出 run the thread: 1 run the thread: 3 run the thread: 2 run the thread: 0 run the thread: 4 run the thread: 7 run the thread: 6 run the thread: 8 run the thread: 5 run the thread: 9 run the thread: 10 run the thread: 12 run the thread: 11 run the thread: 14 run the thread: 13 run the thread: 15 run the thread: 17 run the thread: 16 run the thread: 18 run the thread: 19 run the thread: 20 run the thread: 21 ----all threads done--- Process finished with exit code 0
解析:程序的执行,给我们的感觉是分了5组,这5个同时完成,又同时进5个进去。但是实际的情况是这5个里面如果有3个完成,就会立刻再放3个进去。不会等5个都完成再进去,而是出来几个进去几个。
应用场景
- 信号量适合应用于修改公共变量的值的场景,它适合线程池或连接池,如MySQL中同一时间有多少个并发,能建立多少个连接
- 我们为了保证我的SocketServer,因为Python不会默认现在你启动多少个线程,但是你启动的线程越多,就会把程序拖慢。这里可以用semaphore设置在同一时间放100个连接进来