import threading
import time
# 信号量,多线程中对资源限定访问,可以指定
# 线程运行数,当计数小于0,则其他线程阻塞直到
# 占用资源线程运行结束并释放锁计数+1,其他阻塞线程
# 会继续运行
count_sum = 0
sem = threading.Semaphore(value = 2)
def thread_func(times, sm):
time.sleep(1)
global count_sum
count_sum += times
sm.release() # 运行结束释放锁,计数+1
print("times:{}, count_sum:{}, sem_value:{}".format(times, count_sum, sem._value))
for i in range(10):
sem.acquire() # 计数<=0 会阻塞
task = threading.Thread(target=thread_func, args=(i, sem))
task.start()
python信号量
最新推荐文章于 2024-06-30 23:16:00 发布