生成器是线程安全的吗? [英] Are Generators Threadsafe?

查看:86
本文介绍了生成器是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程程序,在其中创建生成器函数,然后将其传递给新线程.我希望它本质上是共享的/全局的,以便每个线程都可以从生成器获取下一个值.

I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.

使用这样的生成器是否安全,还是会遇到从多个线程访问共享生成器的问题/情况?

Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multiple threads?

如果没有,是否有更好的方法来解决此问题?我需要可以在列表中循环并为任何线程调用它生成下一个值的东西.

If not, is there a better way to approach the problem? I need something that will cycle through a list and produce the next value for whichever thread calls it.

推荐答案

它不是线程安全的;同时调用可能交错,并与局部变量混淆.

It's not thread-safe; simultaneous calls may interleave, and mess with the local variables.

常见的方法是使用主从模式(在PC中现在称为农民工模式").创建第三个线程来生成数据,并在主服务器和从服务器之间添加一个队列,从服务器将从队列中读取数据,而主服务器将向该队列中写入数据.标准队列模块提供必要的线程安全性,并安排阻塞主服务器,直到从服务器准备读取更多数据为止.

The common approach is to use the master-slave pattern (now called farmer-worker pattern in PC). Make a third thread which generates data, and add a Queue between the master and the slaves, where slaves will read from the queue, and the master will write to it. The standard queue module provides the necessary thread safety and arranges to block the master until the slaves are ready to read more data.

这篇关于生成器是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆