I was wondering why reading from memory is not thread-safe. Among what I've seen so far, inter alia this question, reading from memory does not appear to be thread-safe.
I've been coding in Python for a while and now getting into C++. I've never heard that reading in Python is not thread-safe.
Please correct me if I'm wrong, but if not, please tell me why reading from memory is not thread-safe.
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.
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.
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)
It is thread safe if many threads are reading the same location, until no one attempts to write there.
Consider if thread A is reading something at the same time as thread B is writing at the memory being read. It will generate a race condition
. The reading result can become invalid or different from launch to launch
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With