Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is non-thread-safety for?

There are a lot of articles and discussions explaining why it is good to build thread-safe classes. It is said that if multiple threads access e.g. a field at the same time, there can only be some bad consequences. So, what is the point of keeping non thread-safe code? I'm focusing mostly on .NET, but I believe the main reasons are not language-dependent.

E.g. .NET static fields are not thread-safe. What would be the result if they were thread-safe by default? (without a need to perform "manual" locking). What are the benefits of using (actually defaulting to) non-thread-safety?

One thing that comes to my mind is performance (more of a guess, though). It's rather intuitive that, when a function or field doesn't need to be thread-safe, it shouldn't be. However, the question is: what for? Is thread-safety just an additional amount of code you always need to implement? In what scenarios can I be 100% sure that e.g. a field won't be used by two threads at once?

like image 394
pbalaga Avatar asked Jan 07 '11 19:01

pbalaga


1 Answers

Writing thread-safe code:

  1. Requires more skilled developers
  2. Is harder and consumes more coding efforts
  3. Is harder to test and debug
  4. Usually has bigger performance cost

But! Thread-safe code is not always needed. If you can be sure that some piece of code will be accessed by only one thread the list above becomes huge and unnecessary overhead. It is like renting a van when going to neighbor city when there are two of you and not much luggage.

like image 157
Andrey Avatar answered Oct 17 '22 05:10

Andrey