从不同线程读取数据可能会出现错误
我目前正在编写一个使用多线程的程序。为了能够在这些线程之间共享数据,我使用像 threading.Lock 这样的锁来避免运行期间的访问问题。
但我遇到的问题是,我必须为每个数据创建大量锁才能读取该数据。即使我对数据进行“分组”并为它们使用相同的锁,它们也太多了。
所以我问自己:如果一个线程只读取数据而不更改它(这也适用于所有其他线程),是否会发生任何问题?
提前致谢,
I currently program a program which uses multiple threads. To be able to share data across these threads I use Locks like threading.Lock to avoid access problem during run.
But the problem that I got is that I have to create huge amount locks for every data just for reading that data. Even if I 'group' data and use for them the same lock there are too many of them.
So I am asking myself: If a thread just reads data and does not changes it (that also applies to all other threads), are there any problems which can occur?
Thanks in advance,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果所有线程都只是读取数据,那么从不同线程同时访问数据就没有问题,只要读取数据不会改变它即可。更改读取的数据可能会发生在某些数据结构中,
defaultdict
这是一个棘手的例子。如果您有消费者\生产者场景,请考虑使用
Queue.Queue
,一个线程安全的数据结构,允许同时读取和写入。来自 Python 文档:If all your threads just read data, there is no problem accessing the data simultaneously from different threads, as long as reading the data does not change it. Changing the read data can occur in some data structure,
defaultdict
being a tricky example.If you have a consumer\producer scenario, consider using
Queue.Queue
, a thread-safe data structure which allows simultaneous reads and writes. From the Python documentation:假设您有 50 个线程。只要单个线程能够写入数据,那么任何其他读取数据的线程都会产生问题。
例如,一个线程写入数据,然后另一个线程读取该数据。如果存在并发问题,它会在更改之前或之后读取数据。你将无法认出这一点。
只有每个线程都读取,才不会出现问题。
Suppose that you have 50 threads. As long as a single thread is able to write data, then any other thread that reads data can create a problem.
For instance, a thread writes data and then another reads that data. If there is a concurrency problem, it would either read data before or after the change. You wouldn't be able to recognize that.
Only if EVERY thread just reads, you will not have a problem.
我相信你只需要在写入时锁定,这意味着如果你有 20 个线程只读取一个写入,那么你只需要在写入一个正在工作时锁定,将 21 个锁定线程减少到只有一个
I believe you only have to lock if you write that means that if you have 20 threads reading a only one writing then you only have to lock when the writing one is working reducing 21 locking threads to only one