【发布时间】:2011-05-18 03:52:47
【问题描述】:
我有一个队列,当它们被添加到它时,它总是需要准备好处理它们。在队列中的每个项目上运行的函数创建并启动线程以在后台执行操作,以便程序可以去做其他事情。
但是,我在队列中的每个项目上调用的函数只是启动线程然后完成执行,而不管它启动的线程是否完成。因此,在程序处理完最后一项之前,循环将转到队列中的下一项。
这是更好地展示我正在尝试做的事情的代码:
queue = Queue.Queue()
t = threading.Thread(target=worker)
t.start()
def addTask():
queue.put(SomeObject())
def worker():
while True:
try:
# If an item is put onto the queue, immediately execute it (unless
# an item on the queue is still being processed, in which case wait
# for it to complete before moving on to the next item in the queue)
item = queue.get()
runTests(item)
# I want to wait for 'runTests' to complete before moving past this point
except Queue.Empty, err:
# If the queue is empty, just keep running the loop until something
# is put on top of it.
pass
def runTests(args):
op_thread = SomeThread(args)
op_thread.start()
# My problem is once this last line 't.start()' starts the thread,
# the 'runTests' function completes operation, but the operation executed
# by some thread is not yet done executing because it is still running in
# the background. I do not want the 'runTests' function to actually complete
# execution until the operation in thread t is done executing.
"""t.join()"""
# I tried putting this line after 't.start()', but that did not solve anything.
# I have commented it out because it is not necessary to demonstrate what
# I am trying to do, but I just wanted to show that I tried it.
一些注意事项:
这一切都在 PyGTK 应用程序中运行。 'SomeThread' 操作完成后,它会向 GUI 发送回调以显示操作结果。
我不知道这对我遇到的问题有多大影响,但我认为这可能很重要。
【问题讨论】:
-
我不明白这个问题。您可以使用
Thread.join暂停执行,直到线程完成,如果这是您正在寻找的。但是,你的问题很不清楚。 -
您分配 t 两次,一次在全局范围内,一次在 runTests 函数中。这真的是一个有代表性的例子吗?您能否向我们展示一个完整的代码示例来说明您遇到的问题?
-
我的代码实际上并非如此。我试图用更简单的术语来表达我想做的事情,并摆脱了每个函数中发生的所有实际数据处理。无论如何,我正在考虑只写出我想做的伪代码,看看是否有人知道怎么做,因为我患有临界性唐氏综合症,无法正确传达我的问题。
标签: python multithreading queue