题目:有一个南北向的桥,只能容纳一个人,现桥的两边分别有10人和12人,编制一个多线程序让这些人到达对岸,每个人用一个线程表示,桥为共享资源。在过桥的过程中显示谁在过桥及其走向。
import threading
import time
from collections import deque
class Person(threading.Thread):
def __init__(self, id, msg):
threading.Thread.__init__(self)
self.id = id
self.msg = msg
def run(self):
cross(self)
def cross(self):
print(str(self.id) + "\t" + self.msg)
class PersonPool(threading.Thread):
canCross = threading.RLock()
def __init__(self):
threading.Thread.__init__(self)
self.persons = deque([])
self.shutdown = False
def add(self, person):
self.persons.append(person)
def stop(self):
self.shutdown = True
def run(self):
self.waitForPerson()
def waitForPerson(self):
while self.shutdown == False:
PersonPool.canCross.acquire()
while len(self.persons) != 0:
person = self.persons.popleft()
person.cross()
time.sleep(1)
PersonPool.canCross.release()
if __name__ == "__main__":
nsPool = PersonPool()
snPool = PersonPool()
snPool.start()
nsPool.start()
for i in xrange(0, 10):
snPool.add(Person(i, "From North To South"))
for j in xrange(0, 12):
snPool.add(Person(j, "From South To North"))
本文通过Python的多线程实现了一个模拟过桥场景的问题,桥作为共享资源,南北两岸各有不同数量的人群等待过桥,每个行人由单独的线程控制,展示了如何在并发环境中管理共享资源。
412

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



