如果两个线程读取 & 会发生什么?写同一块内存 [英] What happens if two threads read & write the same piece of memory

查看:29
本文介绍了如果两个线程读取 & 会发生什么?写同一块内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,如果两个线程正在从同一块内存中读取数据,并且没有线程正在写入该内存,则该操作是安全的.但是,我不确定如果一个线程正在读取而另一个线程正在写入会发生什么.会发生什么?结果是不确定的吗?或者阅读只是陈旧的?如果过时的读取不是问题,是否可以对变量进行不同步的读写?或者有没有可能是数据被破坏了,读取和写入都不正确,在这种情况下应该始终同步?

It's my understanding that if two threads are reading from the same piece of memory, and no thread is writing to that memory, then the operation is safe. However, I'm not sure what happens if one thread is reading and the other is writing. What would happen? Is the result undefined? Or would the read just be stale? If a stale read is not a concern is it ok to have unsynchronized read-write to a variable? Or is it possible the data would be corrupted, and neither the read nor the write would be correct and one should always synchronize in this case?

我想说的是,我已经了解到这是后一种情况,内存访问竞争导致状态未定义......但我不记得我在哪里学到的,而且我很难是时候在谷歌上找到答案了.我的直觉是在寄存器中操作变量,并且真正的(如在硬件中)并发是不可能的(或者是这样),因此可能发生的最坏情况是陈旧数据,即以下内容:

I want to say that I've learned it is the later case, that a race on memory access leaves the state undefined... but I don't remember where I may have learned that and I'm having a hard time finding the answer on google. My intuition is that a variable is operated on in registers, and that true (as in hardware) concurrency is impossible (or is it), so that the worst that could happen is stale data, i.e. the following:

WriteThread: copy value from memory to register
WriteThread: update value in register
ReadThread:  copy value of memory to register
WriteThread: write new value to memory

此时读取线程具有陈旧数据.

At which point the read thread has stale data.

推荐答案

结果未定义.损坏的数据是完全可能的.对于一个明显的示例,请考虑由 32 位处理器操作的 64 位值.让我们假设这个值是一个简单的计数器,当低 32 位包含 0xffffffff 时我们增加它.增量产生 0x00000000.当我们检测到这一点时,我们增加上面的单词.但是,如果某个其他线程读取了下位字递增和上位字递增之间的值,则它们会得到一个上位字未递增的值,但下位字设置为 0 —— 一个完全不同的值从增量完成之前之前的情况来看.

The result is undefined. Corrupted data is entirely possible. For an obvious example, consider a 64-bit value being manipulated by a 32-bit processor. Let's assume the value is a simple counter, and we increment it when the lower 32-bits contain 0xffffffff. The increment produces 0x00000000. When we detect that, we increment the upper word. If, however, some other thread read the value between the time the lower word was incremented and the upper word was incremented, they get a value with an un-incremented upper word, but the lower word set to 0 -- a value completely different from what it would have been either before or after the increment is complete.

这篇关于如果两个线程读取 & 会发生什么?写同一块内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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