“Thread safe” is a slightly unfortunate term because it does not really have a clear definition. Basically, this means that certain operations on an object are guaranteed to behave reasonably when the object is managed through multiple threads.
Consider the simplest example: a counter. Suppose you have two threads that increment a counter. If the sequence of events goes:
- Stream one is read from the counter, gets zero.
- To enter two readings from the counter, gets zero.
- Stream one increases zero, writes one for the fight.
- Enter two increments of zero, writes one for the fight.
Then notice how the counter “lost” one of the increments. Simple increment operations on counters are not thread safe; to make them thread safe, you can use locks or InterlockedIncrement.
Similar to the queue. Non-threadafe-queues can "lose" queues in the same way as non-threadafe queues can lose increments. Worse, non-thread-safe queues can even trash or create crazy results if you use them in a multi-threaded scenario incorrectly.
The difficulty with thread safety is that it is not clearly defined. Does this mean that it doesn’t fail? Does this mean that reasonable results will be obtained? For example, suppose you have a threadafe collection. Is this code correct?
if (!collection.IsEmpty) Console.WriteLine(collection[0]);
Not. Even if the collection is "streaming", this does not mean that this code is correct; another thread could make the collection empty after checking, but before writing, and therefore this code may crash even if the object is supposedly “thread safe”. In fact, determining that each appropriate combination of operations is thread safe is an extremely complex problem.
Now, to come to your real situation: anyone who tells you “you should use the Queue class is better because it is thread safe” probably does not have a clear idea of ​​what they are talking about. First, the queue is not thread safe. Secondly, regardless of whether Queise is thread safe or not, it doesn’t matter if you use only an object in a single thread! If you have a collection that will be accessed by several threads, then, as I indicated in my example above, you have to solve a very difficult problem, regardless of whether the collection itself is "thread safe". You must determine that each combination of operations that you perform in the collection is also thread safe. This is a very difficult problem, and if this is the one you are facing, then you should use the services of an expert on this complex topic.
Eric Lippert
source share