美文网首页
python:多线程使用生成器提示ValueError: gen

python:多线程使用生成器提示ValueError: gen

作者: Xpitz | 来源:发表于2018-12-11 15:51 被阅读0次

欢迎关注我的微信公众号:「阿拉平平」

最近写脚本时涉及到了多线程和生成器,在使用过程中遇到了数据竞争的问题,特此记录下。

在执行脚本时提示以下错误:
ValueError: generator already executing

多线程同时请求生成器数据(即同时调用next方法)就会引发该错误,所以只要在调用next方法时加个就可以解决。

在脚本开头处加入:
class threadsafe_iter:
    """Takes an iterator/generator and makes it thread-safe by
    serializing call to the `next` method of given iterator/generator.
    """

    def __init__(self, it):
        self.it = it
        self.lock = threading.Lock()

    def __iter__(self):
        return self

    def __next__(self): # python3
        with self.lock:
            return self.it.__next__()
  
     # def next(self): # python2
     #     with self.lock:
     #       return self.it.next()



def threadsafe_generator(f):
    """A decorator that takes a generator function and makes it thread-safe.
    """

    def g(*a, **kw):
        return threadsafe_iter(f(*a, **kw))

    return g

说明:

相关文章

网友评论

      本文标题:python:多线程使用生成器提示ValueError: gen

      本文链接:https://www.haomeiwen.com/subject/opfehqtx.html