国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python多線程經(jīng)典問題之乘客做公交車算法實(shí)例

2020-02-23 04:27:39
字體:
供稿:網(wǎng)友

本文實(shí)例講述了Python多線程經(jīng)典問題之乘客做公交車算法。分享給大家供大家參考,具體如下:

問題描述:

乘客乘坐公交車問題,司機(jī),乘客,售票員協(xié)同工作,通過多線程模擬三者的工作。
司機(jī):開車,停車
售票員:打開車門,關(guān)閉車門
乘客:上車,下車

用Python的Event做線程同步通信,代碼如下:

# *-* coding:gb2312 *-*import threadingimport timestationName=("車站0","車站1","車站2","車站3","車站4","車站5","車站6")currentStationIndex = -1eventBusStop = threading.Event()eventClosedDoor = threading.Event()eventOpenedDoor = threading.Event()stationCount = len(stationName)class Passenger(threading.Thread):  def __init__(self,no,getonStation,getoffStation):    self.no =no    self.getonStation=getonStation    self.getoffStation=getoffStation    threading.Thread.__init__(self)  def run(self):    bExit= False    global currentStationIndex    global stationCount    bAlreadyGetOnStation = False    while not bExit:      eventOpenedDoor.wait()      if self.getonStation == currentStationIndex and bAlreadyGetOnStation == False:        print "乘客%d在%s上車" %(self.no,stationName[currentStationIndex])        bAlreadyGetOnStation =True      elif self.getoffStation == currentStationIndex:        print "乘客%d在%s下車" %(self.no,stationName[currentStationIndex])        bExit = True      time.sleep(1)class Driver(threading.Thread):  def run(self):    bExit= False    global currentStationIndex    global stationCount    while not bExit:      print "司機(jī): 公交車開始行駛....."      time.sleep(5)      currentStationIndex += 1      print "司機(jī): 到站 ",stationName[currentStationIndex]      eventBusStop.set()      eventClosedDoor.wait()      eventClosedDoor.clear()      if currentStationIndex == stationCount-1:        bExit= Trueclass Conductor(threading.Thread):  def run(self):    bExit= False    global currentStationIndex    global stationCount    while not bExit:      eventBusStop.wait()      eventBusStop.clear()      print "售票員打開車門:%s到了" %(stationName[currentStationIndex])      eventOpenedDoor.set()      time.sleep(5)      print "售票員關(guān)閉車門"      eventOpenedDoor.clear()      eventClosedDoor.set()      if currentStationIndex == stationCount-1:        bExit = Truedef test():  passPool=[]  passPool.append(Passenger(0,0,3))  passPool.append(Passenger(1,1,3))  passPool.append(Passenger(2,2,4))  passPool.append(Passenger(3,0,5))  passPool.append(Passenger(4,1,3))  passPool.append(Passenger(5,2,4))  passPool.append(Passenger(6,4,5))  passPool.append(Passenger(7,0,2))  passPool.append(Passenger(8,1,3))  passPool.append(Conductor())  passPool.append(Driver())  leng = len(passPool)  for i in range(leng):    passPool[i].start()if __name__=='__main__':  test()

輸出結(jié)果如下:

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 广西| 台州市| 兴宁市| 祁门县| 宝清县| 曲阜市| 榆中县| 遂平县| 黑龙江省| 南和县| 青海省| 奉新县| 左贡县| 桐乡市| 临猗县| 缙云县| 于都县| 尉氏县| 翁源县| 黄冈市| 家居| 东兴市| 泰州市| 肃北| 和林格尔县| 景泰县| 夏邑县| 钟祥市| 乌鲁木齐县| 县级市| 大同县| 南宁市| 敖汉旗| 五大连池市| 喀什市| 龙岩市| 融水| 五河县| 孟州市| 沙雅县| 沙湾县|