What is non-thread-safety for? What is non-thread-safety for? multithreading multithreading

What is non-thread-safety for?


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.


Thread safety comes with costs - you need to lock fields that might cause problems if accessed simultaneously.

In applications that have no use of threads, but need high performance when every cpu cycle counts, there is no reason to have safe-thread classes.


So, what is the point of keeping non thread-safe code?

Cost. Like you assumed, there usually is a penalty in performance.

Also, writing thread-safe code is more difficult and time consuming.