如果两个线程读取&写相同的内存 [英] What happens if two threads read & write the same piece of memory

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

问题描述

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

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?

我想说我我已经知道是后一种情况,关于内存访问的竞赛使状态处于未定义状态……但是我不记得我可能在哪里学到的,而且我很难在google上找到答案。我的直觉是,变量是在寄存器中操作的,并且真正的(如在硬件中)并发是不可能的(或者是并发),因此可能发生的最坏情况是过时的数据,即以下内容:

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天全站免登陆