从线程中生成项

4 投票
2 回答
6634 浏览
提问于 2025-04-16 19:25
from threading import Thread
import time
print 'start of script'

class MyThread(Thread):
    def __init__(self, start, end):
        self.start = start
        self.end = end
    def run(self):
        for i in xrange(self.start,self.end):
            yield i




my_threads = []

my_thread = MyThread(1,6)
my_thread.start()
my_threads.append(my_thread)

my_thread = MyThread(6,11)
my_thread.start()
my_threads.append(my_thread)

my_thread = MyThread(11,16)
my_thread.start()
my_threads.append(my_thread)


for t in my_threads:
    print t.join()

print 'end of script'

我该怎么做才能正确实现这个呢?我想打印出数字范围:range(1,16),这些数字是从一个在不同线程中运行的函数的输出中获取的。

我明白,由于在不同线程中运行函数的特性,我不会按顺序得到这些数字。

我也知道我可以直接在线程的函数里打印这些数字,但这不是我想要的,我想在主线程或代码的主要部分打印我得到的结果。

2 个回答

0

我觉得你想要的东西是一个队列。把一个队列传给你的线程,然后不是直接返回值,而是把值放进队列里(myqueue.put(i))。这样你就可以在主线程里取出这些值(myqueue.get())。

5

线程是不能返回值的,所以你无法像希望的那样把值传回主线程。如果你让你的脚本运行起来(你需要把start这个变量改个名字,因为现在它和start方法冲突了),你会发现t.join()的返回值是None。解决这个问题的一个常见方法是使用队列(Queue),就像在这个类似的问题中提到的那样:线程返回值

在你的情况下,不是调用yield i,而是应该调用queue.put(i),其中queue是你在创建时传入的Queue.Queue。然后在主线程中加一个循环,等到所有线程都结束:

while True:
    try:
        print outqueue.get(True, 1)
    except Empty:
        break

for t in my_threads:
    print t.join()

这样会等待最多1秒钟来获取新项目,如果没有新项目,就会抛出Empty,然后跳出循环。

撰写回答