"is this use of the generic list thread safe" Code Answer


is a read operation that iterates the queue and accesses the corresponding items in the list thread safe?

is it documented as being thread safe?

if no, then it is foolish to treat it as thread safe, even if it is in this implementation by accident. thread safety should be by design.

sharing memory across threads is a bad idea in the first place; if you don't do it then you don't have to ask whether the operation is thread safe.

if you have to do it then use a collection designed for shared memory access.

if you can't do that then use a lock. locks are cheap if uncontended.

if you have a performance problem because your locks are contended all the time then fix that problem by changing your threading architecture rather than trying to do dangerous and foolish things like low-lock code. no one writes low-lock code correctly except for a handful of experts. (i am not one of them; i don't write low-lock code either.)

even if the list is resized when it is being indexed, i am only accessing an item that already exists, so it does not matter whether it is read from the old array or the new array.

that's the wrong way to think about it. the right way to think about it is:

if the list is resized then the list's internal data structures are being mutated. it is possible that the internal data structure is mutated into an inconsistent form halfway through the mutation, that will be made consistent by the time the mutation is finished. therefore my reader can see this inconsistent state from another thread, which makes the behaviour of my entire program unpredictable. it could crash, it could go into an infinite loop, it could corrupt other data structures, i don't know, because i'm running code that assumes a consistent state in a world with inconsistent state.

By Anthony Lethuillier on April 4 2022

Answers related to “is this use of the generic list thread safe”

Only authorized users can answer the Search term. Please sign in first, or register a free account.