Are you saying this is always wrong? I thought that depended on the use case at hand.
Are you saying this is always wrong? I thought that depended on the use case at hand.
To prevent tearing, you can use a regular mutex (only one reader at a time), or https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock, which allows multiple concurrent readers, but has more overhead than a regular mutex, and when contention occurs can prioritize either readers or writers. If you don't want readers or writers to block, you can use (for <=64-bit values) atomic reads and writes, (for single writers and readers) triple buffers, or (in general) RCU or hazard pointers.
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.