3 ms·
> reads are always unsafe when there is a possibility of writes. That is correct for any reads that could race against a write. Writes must be synchronized wit
by haberman 5y ago
> reads are always unsafe when there is a possibility of writes.
That is correct for any reads that could race against a write. Writes must be synchronized with all other operations. But reads may proceed in parallel with other reads without synchronization.
For example, if you have an object that is written in the thread where it is constructed, and only released to other threads once the mutation is complete, then you do not need to synchronize readers. Because the nature of the data flow ensures that none of the writes can race with the reads.
> So to me this just reads as, "the caller has to manage all the thread safety for all the accesses"
Not all accesses. Just the ones where a writer may race with another write or a read.
> Or is there an example of some c++ that is not even "thread-compatible" once the caller has accepted the burden of synchronization?
Thread-unsafe types do not even allow two reads to be unsynchronized.
- efokschaner 5y agoThanks for the response. I think my disagreement is in describing that as "without synchronization", somewhere the caller is somehow ensuring there are no writes during their safe parallel reads.
- haberman 5y agoI agree that the writes are synchronized with the reads in my example. But the reads are totally unsynchronized with respect to other reads, in every sense. That is what thread-compatibility guarantees you: concurrent reads without synchronization. A thread-unsafe type doesn't allow even that much.
- efokschaner 5y agoThanks, that makes sense.
- randomNumber7 5y agoIsn't it always safe if you only read? I can't imagine an example where a race occurs when all threads are just reading.
- haberman 5y ago"Read" here is shorthand for "call a const method". You can write const methods that are not safe to call concurrently: for example, they could use "mutable" or "const cast" to perform mutation, or they could access a non-const pointer to shared state. If a type had a const method like this, the type would no longer be considered thread-compatible.