代码段1:
1 # -*-coding:utf-8 -*- 2 from threading import Thread, BoundedSemaphore 3 from datetime import datetime 4 import time 5 6 # 定义一个函数 7 def showtime(signal): 8 print(datetime.now()) 9 time.sleep(2) 10 signal.release() 11 12 # 创建一个有界信号量对象,内部计数器的初始值为3 13 bsema = BoundedSemaphore(3) 14 # 创建并启动10个线程 15 with bsema: 16 for n in range(10): 17 bsema.acquire() 18 t = Thread(target=showtime,args=(bsema,)) 19 t.start()
代码段2:
1 # -*-coding:utf-8 -*- 2 from threading import Thread, BoundedSemaphore 3 from datetime import datetime 4 import time 5 6 # 定义一个函数 7 def showtime(signal): 8 print(datetime.now()) 9 time.sleep(2) 10 signal.release() 11 12 # 创建一个有界信号量对象,内部计数器的初始值为3 13 bsema = BoundedSemaphore(3) 14 # 创建并启动10个线程由于信号量初始值为3,所以每次只有3个线程并发执行 15 for n in range(10): 16 bsema.acquire() 17 t = Thread(target=showtime,args=(bsema,)) 18 t.start()
代码段1的结果是每次只有2个线程在执行函数showtime,但是代码段2的结果是每次有3个线程在执行showtime函数,原因是什么?
代码段1执行结果:
2022-02-06 00:35:46.583684
2022-02-06 00:35:46.583684
2022-02-06 00:35:48.598238
2022-02-06 00:35:48.599237
2022-02-06 00:35:50.607590
2022-02-06 00:35:50.608596
2022-02-06 00:35:52.622436
2022-02-06 00:35:52.623437
2022-02-06 00:35:54.630541
2022-02-06 00:35:54.631551
代码段2执行结果:
2022-02-06 00:32:59.856888
2022-02-06 00:32:59.857888
2022-02-06 00:32:59.857888
2022-02-06 00:33:01.862122
2022-02-06 00:33:01.863158
2022-02-06 00:33:01.864120
2022-02-06 00:33:03.865883
2022-02-06 00:33:03.866844
2022-02-06 00:33:03.867841
2022-02-06 00:33:05.878067