0

铁路上只有两列火车(同时)的最简单方法是什么?我的英语不好。这是我解释它的唯一方法。我知道我应该使用队列?我找不到我的语言的信息

谢谢!

1>去,2>去。3,4等等。1>完成,3>去(第四个还在等待)..

from threading import Thread
import time
import random

def trains(city):
    print city, 'start'

    for count in range(1,3):
        delay = random.randrange(5,10)
        print city, 'delay', delay
        time.sleep(delay)

    print city, 'end'


cities = ['prague', 'london', 'berlin', 'moscow']
threadlist = []

for city in cities:                             
    t = Thread(target=trains, args=(city,))
    t.start()
    threadlist.append(t)


for b in threadlist:
    b.join()
4

1 回答 1

0

我将在这里猜测一些事情:

from threading import Thread, Lock, BoundedSemaphore
import time
import random

def trains(city):
    with railroads:
        with iolock:
            print city, 'start'

        for count in range(1,3):
            delay = random.randrange(5,10)
            with iolock:
                print city, 'delay', delay
            time.sleep(delay)

        with iolock:
            print city, 'end'


cities = ['prague', 'london', 'berlin', 'moscow']
threadlist = []

iolock = Lock()
railroads = BoundedSemaphore(2)

for city in cities:                             
    t = Thread(target=trains, args=(city,))
    t.start()
    threadlist.append(t)


for b in threadlist:
    b.join()

的目的iolock是停止终端中的混合输出:一次只打印 1 个线程。的目的railroads是允许最多两个线程同时进入代码体。这是示例输出。请注意,“prague”和“london”恰好在一开始运行,但“berlin”不会在“london”结束之前启动。然后“莫斯科”直到“布拉格”结束才开始:

prague start
london start
prague delay 8
london delay 5
london delay 6
prague delay 5
london end
berlin start
berlin delay 8
prague end
moscow start
moscow delay 8
berlin delay 6
moscow delay 7
berlin end
moscow end
于 2013-10-03T18:09:46.370 回答