generators can be shared between threads, but they cannot be resumed from two threads at the same time.
当两个线程同时调用一个生成器的next方法时就会引发“generator already executing”异常。
解决方法:加锁。
如下代码所示:
import threading class threadsafe_generator: """Takes an generator and makes it thread-safe by serializing call to the `next` method of given generator. """ def __init__(self, gen): self.gen = gen self.lock = threading.Lock() def __iter__(self): return self.next() def next(self): with self.lock: return self.gen.next() # 定义我们的生成器 def all_keywords(): for row in csv.reader(open('companies.csv')): if row[0]: yield row[0] # 将其转换为线程安全的 keywords = threadsafe_generator(all_keywords()) # 然后在线程中就可以随意地使用keywords.next()而不必担心"generator already executing"异常了。
呵呵,谢谢
VaTG790i.最好的<a href=http://www.kyfei.com>网站推广软件</a>,
非常好
....................
;ui;普i;uighur;ui;ui;个
在unix网络编程中看到了关于TCP/IP的一些内容,我感觉还是写的不够。正在下载中,一定
下载地址呢