使用close() 方法结束生成器。
1 2 3 4 5 6 7 | 上面例子中f.close()则关闭了生成器。 >>> f.close() >>> next (f) Traceback (most recent call last): File "<pyshell#92>" , line 1 , in <module> next (f) StopIteration |
举例:一个线程正在从生成器中依次生成元素,处理某一事务, 另一线程 可以通过send函数发送指令或数据给生成器,从而影响原来使用生成器线程的事务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import threading import time class Thread1(threading.Thread): def __init__( self , name, fib): threading.Thread.__init__( self ) self .name = name self .fib = fib def run( self ): for i in range ( 10 ): try : time.sleep( 1 ) print ( next ( self .fib)) except StopIteration: print ( "over" ) break class Thread2(threading.Thread): def __init__( self , name, fib): threading.Thread.__init__( self ) self .name = name self .fib = fib def run( self ): time.sleep( 3 ) try : self .fib.send( "quit" ) # self.fib.close() except StopIteration: print ( '结束生成器' ) def Fib(): a,b = 0 , 1 while True : r = yield b if r = = 'quit' : break a,b = b,a + b a = Fib() t1 = Thread1( 'thread1' ,a) t2 = Thread2( 'thread2' ,a) t1.start() t2.start() |