What is Thread-Safe? 🤔
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:
- 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.
- 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 in the internet that can help you to design for your problem. But I have found these two ways that is more realistic and popular approach (also I followed these also 😋).
- Use lock.
- Make your class immutable.
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.
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 two topics, I already have an article on Race Condition.
Happy threading 🎈🎈🎈.