且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么读取不是线程安全的?

更新时间:2022-03-03 08:24:14

读取是线程安全的,没有问题......直到某些内容写入您正在读取的位置,然后...好吧,希望您会在数据更改之前进行读取,或者在数据更改之后进行读取(在这种情况下,无需担心),但是有时,当您确实不想要它时,您将在写入过程中进行一半的读取,然后您将获得竞争垃圾数据.

Reading is thread safe, no problems..... until something writes to the location you're reading from, and then... well, hopefully you'll read before the data was changed, or read after the data was changed (in these cases, no worries), but sometimes, just when you really don't want it, you'll read half-way through the write and then you'll get compete garbage data.

减轻这种情况的方法是确保仅在任何写入之前或之后读取,这需要您检查是否正在发生写入,并因此使用某种同步锁.但是,这会使事情变慢,因为您显然正在检查锁,然后读取而不是读取.如果您正在使用原始数据类型(例如int),则可以使用CPU同步来显着加快此速度.

The way to mitigate this is to ensure that you only read either before or after any writes, which requires you to check that a write is occurring and thus use a synchronisation lock of some sort. This makes things slower though, as you're obviously checking the lock and then reading instead of reading. If you're working with primitive data types (an int for example) then you can use a CPU synchronisation to speed this up dramatically.

与Python一样,语言运行时总是会为您同步python数据,如果不是,那么迟早会出现相同的线程读取问题.(快速的Google说是的, Python也会遇到相同的问题,如果您不小心的话)

As fr Python, chances are python data is always synchronised for you by the language runtime, if it isn't then you will get the same thread read problems sooner or later. (quick google says yes, Python will suffer the same problems is you're not careful)