我有一个线程数组。他们每个人都不断地调用run方法。在每个运行方法结束时,我希望它们暂停并等待。
如何让线程一次执行一个,然后在所有线程完成后继续循环?我需要它们始终按顺序执行(即:1、2、3、4 - 1、2、3、4...)
我目前正在使用threading.Event,但结果不一致。
谢谢
更新
感谢大家迄今为止的回答。
我正在用 python 编写类似于 Robocode 的东西。玩家对一个机器人进行编程,机器人之间进行战斗,直到剩下一个。每次“转动”后,机器人都会“暂停”,然后更新并绘制到屏幕上。然后他们都开始新一轮。
示例:
# Bot extends threading.Thread
class DemoBot(Bot):
def __init__(self):
super(DemoBot, self).__init__()
def run(self):
while True:
self.moveForward(100)
self.turnLeft(90)
如您所见,机器人处于无限循环中。在 moveForward 方法中,机器人将向前移动 100px。但为了正确更新屏幕,我必须移动一次,暂停,更新,然后再次移动。这就是为什么我需要能够在机器人完成后“暂停”机器人,并让程序在更新屏幕之前等待其他程序。
希望这更有意义。
最佳答案
您的描述似乎暗示您不希望线程同时执行,这会让人质疑您为什么首先使用线程。
对于您为什么要这样做,我感觉到有两个可能的答案。
第一种可能性是您试图阻止线程同时处理某种共享资源。如果是这种情况,您可能需要使用 threading.Lock 或 threading.RLock 来锁定关键代码部分。 (下面的示例是针对 python 2.5+ 编写的,您需要在较旧的 python 上使用显式锁获取/释放)
from __future__ import with_statement # only needed on python 2.5
from threading import Lock
lock = Lock()
def worker1():
#noncritical code
with lock:
pass # critical code in here
def worker2():
with lock:
critical_code
但是,这不会强制执行任何类型的排序。当多个线程尝试获取锁时,除了一个线程之外的所有线程都会阻塞(并且下一个获取锁的线程不确定)
您提到订购的事实让我认为您正在进行某种生产者-消费者循环。也就是说,一个线程生成一些输出,下一个线程需要处理该输出。您可以使用queue.Queue在线程之间提供数据并让它们醒来以吞噬下一位数据。
from queue import Queue
one_to_two = Queue(maxsize=10)
def worker1():
while i_have_some_data_stream:
data = get_data_from_somewhere()
modified_data = munge_data_somehow(data)
one_to_two.put(modified_data) #blocks only if queue is currently full
def worker2():
while True:
data = one_to_two.get() # blocks until data available
# do something with data
# Optionally, put this newly processed data into the next queue.
队列是一个强大的原语,可让您在线程之间传递消息并实现有界的生产者-消费者。如果这是您的用例,那么队列将比尝试手动同步线程的顺序更有效。
关于Python 线程暂停和等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2017261/