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'
如何正确执行此操作? 我试图打印的数字:范围(1,16),其中我从一个函数的输出得到这个数字运行在一个单独的线程。从线程收益项目
我明白,我不会得到这个范围数字按顺序排列,就像在单独的线程中运行的函数的性质一样
我也知道我可以简单地在线程的函数本身中打印它们,但那不是重点,我想打印我已经输出的东西在我的代码的主线程或主要部分。
它的工作..然而,我想使用YIELD的原因是远离大变量,所以我想保持q = Queue.Queue(2),然后我做q.get(真),但它滞后和从不打印?我怎样才能让队列一次只保留2个项目,并且仍能获得我想要的所有值? – MistahX 2011-06-12 23:03:23
那么'q.get(True)'会永远阻塞,所以当你的发生器完成时,没有任何东西会被打印出来,它会永远坐着。同样用'q = Queue.Queue(2)'初始化'q'将限制你的'Queue'为2个对象,你的'q.put(i)'调用阻塞直到有空间。我不确定你在问什么,但另一种实现它的方式是在队列上永远保留'Queue'块,但是放一些东西表明你的生产者已经完成了'Queue'并且拥有当看到所有生产者完成时,主线程跳出while循环。 – Hoons 2011-06-13 16:36:02