从线程中生成项目

Mis*_*ahX 4 python

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'
Run Code Online (Sandbox Code Playgroud)

我怎样才能正确地做到这一点?我正在尝试打印数字:范围(1,16),其中我从在单独线程中运行的函数的输出中获取该数字。

我知道我不会按顺序获得这个数字范围,因为函数的本质是在单独的线程中运行。

我也知道我可以简单地在线程函数本身中打印它们,但这不是重点,我想打印我在主线程或代码的主要部分中产生的内容。

Hoo*_*ons 5

线程不返回值,因此您将无法按照您希望的方式将值返回到主线程。如果您要运行脚本(您需要将start变量的名称更改为其他名称,因为您正在隐藏该方法start),您会发现 的返回值为。解决此问题的常见方法是使用队列,正如类似问题中所建议的那样:Return value from threadt.join()None

yield i在您的情况下,我不会调用,而是调用构造期间传入的queue.put(i)位置,然后在加入线程之前在主线程中有一个循环:queueQueue.Queue

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

for t in my_threads:
    print t.join()
Run Code Online (Sandbox Code Playgroud)

Empty在抛出并跳出 while 循环之前,它将等待最多 1 秒的新项目。