2+ 线程写入/读取变量的真正危险 [英] Real dangers of 2+ threads writing/reading a variable

查看:31
本文介绍了2+ 线程写入/读取变量的真正危险的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时读/写单个变量的真正危险是什么?

What are the real dangers of simultaneous read/write to a single variable?

如果我使用一个线程写入变量,另一个线程在 while 循环中读取变量,并且在写入时读取变量并且使用旧值没有危险,那么这里还有什么危险?

If I use one thread to write a variable and another to read the variable in a while loop and there is no danger if the variable is read while being written and an old value is used what else is a danger here?

同时读/写是否会导致线程崩溃,或者当发生精确的同时读/写时,底层会发生什么?

Can a simultaneous read/write cause a thread crash or what happens on the low level when an exact simultaneous read/write occurs?

推荐答案

如果两个线程在没有适当同步的情况下访问一个变量,并且这些访问中至少有一个是写操作,那么您就会出现数据竞争和未定义的行为.

If two threads access a variable without suitable synchronization, and at least one of those accesses is a write then you have a data race and undefined behaviour.

未定义行为的表现方式完全取决于实现.在大多数现代架构中,您不会从硬件中获得陷阱或异常或任何东西,它会读取某些内容,或存储某些内容.问题是,它不一定会读取或写入您期望的内容.

How undefined behaviour manifests is entirely implementation dependent. On most modern architectures, you won't get a trap or exception or anything from the hardware, and it will read something, or store something. The thing is, it won't necessarily read or write what you expected.

例如使用两个线程递增变量,您可能会错过计数,如我在 devx 上的文章中所述:http://www.devx.com/cplus/Article/42725

e.g. with two threads incrementing a variable, you can miss counts, as described in my article at devx: http://www.devx.com/cplus/Article/42725

对于单个写入器和单个读取器,最常见的结果是读取器看到过时的值,但如果更新需要多个周期,或者变量被拆分,您也可能看到部分更新的值缓存行.然后会发生什么取决于你用它做什么——如果它是一个指针并且你得到了一个部分更新的值,那么它可能不是一个有效的指针,无论如何都不会指向你想要的,然后你可能由于取消引用无效的指针值而导致任何类型的损坏或错误.如果错误的指针值恰好指向内存映射的 I/O 寄存器,这可能包括格式化硬盘或其他不良后果......

For a single writer and a single reader, the most common outcome will be that reader sees a stale value, but you might also see a partially-updated value if the update requires more than one cycle, or the variable is split across cache lines. What happens then depends on what you do with it --- if it's a pointer and you get a partially updated value then it might not be a valid pointer, and won't point to what you intended it to anyway, and then you might get any kind of corruption or error due to dereferencing an invalid pointer value. This may include formatting your hard disk or other bad consequences if the bad pointer value just happens to point to a memory mapped I/O register....

这篇关于2+ 线程写入/读取变量的真正危险的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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