What is Thread-Safe? ๐Ÿค”

Pritom Purkayasta
2 min readJul 21, 2021

To control the abnormal behavior of an object in a multi-threaded environment is called Thread Safety.

Thread-safety is a computer programming concept applicable to multi-threaded programs which manipulate shared data structures in a manner that makes it safe execution in a multi-threaded environment.

It is not easy to determine if a piece of code is thread-safe or not. However, there are several indicators that suggest the need for careful examination to see if it is unsafe:

  • Accessing global variables or the heap.
  • Allocating/freeing resources that have global limits (files, sub-processes, etc.)
  • Indirect accesses through handles or pointers

if a method (instance or static) only references variables scoped within that method then it is thread-safe because each thread has its own stack Stackoverflow

Problem Set Example:

  1. Suppose you have a list that is doing some calculation and you are doing it by throwing parallel execution to make it faster, okay but the problem is you have to have some counter to show the progress. If you are going to use any shared variable in a multi-threaded environment itโ€™s not going to show you the accurate result and that makes absolute sense. Here comes the thread-safe concept.
  2. Another example can be, you have a list instance that will add some instance to it from a function. Now you have wrapped it up with some calculation towards it. Thatโ€™s what you do for a single thread / synchronize operation. But you want to do this as fast as possible so ended up throwing some threads to do this task as efficiently as possible. But the moment you introduced multi-thread with this code, you will end up seeing the wrong object adding to your list instance.

To write thread-safe code, there are many solutions on the internet that can help you to design for your problem. But I have found these two ways that are more realistic and popular approach (also I followed these also ๐Ÿ˜‹).

  • Use lock.
  • Make your class immutable.

Solution time:

  1. To display a counter in a multi-threaded procedure you will need a thread-safe counter. Microsoft already provided this out of the box. You can check out Interlocked.
  2. To access any list structure from a concurrent program, you will need something like a concurrent supported list, right? Hold your horses, Microsoft also provided this namespace to solve this issue ConcurrentCollections.

Extras: If you can make your code thread-safe you will remove these two problems also.

  • Race condition.
  • Deadlock.

If you want to know more about these, I have an article for you already :).

Happy threading ๐ŸŽˆ๐ŸŽˆ๐ŸŽˆ.

Originally published at https://pritompurkayasta.me.

--

--

Pritom Purkayasta

if you like the content, you know what to do ๐ŸŽ‰โœ”