Hacker News new | ask | show | jobs
by ReactiveJelly 1544 days ago
If the value is small enough, like 1 byte, and you know for a fact that your CPU + RAM will always be able to update it atomically, then yes technically you could get away with not locking on reads.

BUT, for large values (structs) you will end up getting ragged reads if another thread is writing at the same time. And if another thread is not writing at the same time, what's the harm in locking for reads? Modern mutexes lock fast if there's no contention.

BUT ALSO, many operations are actually a read, followed by a related write. If you don't lock on reads, it's easy to accidentally compose multiple small, correct functions, into a large, incorrect function.

1 comments

Your comment reinforces nyanpasu64 point that the average C++ developer doesn't understand multithreading. Your comment is wrong in that it is never correct in a standard conforming C++ program to read and write to the same object from different threads without the use of a memory barrier, even if the CPU + RAM supports it. The C++ compiler itself will not support such an access pattern and the compiler may reorder instructions that are not protected by a barrier in such a way that results in undefined memory access.

https://en.cppreference.com/w/cpp/language/memory_model