|
|
|
|
|
by nyanpasu64
1544 days ago
|
|
If you only lock on writes rather than reads, it prevents two writers from colliding, but readers can see torn data (a mix of old and new states). Technically speaking, if either the write or read is non-atomic, this is outright undefined behavior, and it's legal for the compiler to generate (eg. reading) code which assumes concurrent writes never happen and misbehaves if they do (for example, the reader thread reading the value twice, expecting the value to be the same, and misbehaving if it's not). 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. |
|