`
yangyi
  • 浏览: 112834 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

多线程过桥的问题

阅读更多
题目:有一个南北向的桥,只能容纳一个人,现桥的两边分别有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"))
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics