简体   繁体   English

python队列多线程

[英]python Queue multithreading

What is the simplest way to have only two trains(in the same time) on the railroad. 在铁路上只有两列火车(同时)的最简单方法是什么。 My english is bad. 我的英语不好。 this is only way how I can explain it. 这是我能解释的唯一方法。 I know I should use Queue? 我知道我应该使用Queue吗? I can't find info in my language 我找不到我所用语言的信息

Thank you! 谢谢!

1>go, 2>go. 1>开始,2>开始。 3,4wait. 3,4wait。 1>finish, 3>go (4th still wait) .. 1>完成,3>执行(第4个仍在等待)..

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()

I'm going to guess at some things here: 我将在这里猜测一些事情:

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()

The purpose of iolock is to stop mixed-up output in your terminal: only 1 thread prints at a time. iolock的目的是在终端中停止混合输出:一次仅打印1个线程。 The purpose of railroads is to allow at most two threads to enter the body of the code simultaneously. railroads的目的是允许最多两个线程同时进入代码主体。 Here's sample output. 这是示例输出。 Note that "prague" and "london" happen to run at first, but "berlin" doesn't start before "london" ends. 请注意,“布拉格”和“伦敦”刚开始运行,但是“柏林”在“伦敦”结束之前没有开始。 Then "moscow" doesn't start until "prague" ends: 然后,直到“布拉格”结束,“ moscow”才开始:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM