把源代码抄了一遍,姑且认为学习吧
import time
from threading import Condition,Thread
class MySemaphore:
def __init__(self,value=1):
self._value = value
self._condition = Condition()
def acquire(self):
with self._condition:
while self._value==0:
self._condition.wait()
else:
self._value-=1
def release(self):
with self._condition:
self._value += 1
self._condition.notify()
sem = MySemaphore(3)
def mythred():
sem.acquire()
time.sleep(2)
print('gogogo !!!')
sem.release()
for i in range(1,22):
t = Thread(target=mythred)
t.start()

本文通过自定义信号量类MySemaphore演示了如何在Python中使用线程进行资源控制。信号量用于同步多个线程对共享资源的访问,避免竞态条件。通过创建并调用21个线程,展示信号量如何限制同时运行的线程数量,确保资源不会被过度消耗。
1088

被折叠的 条评论
为什么被折叠?



