Understanding synchronization primitives
Every time you write single-threaded code, any method execution occurs sequentially and requires no special action from the developer. On the other hand, when some code is executed on a separate thread, synchronization is needed to ensure that we avoid two dangerous concurrency conditions—race and deadlock. These categories of problems must be carefully avoided during design because their detection is difficult and they may occur occasionally.
A race condition is a situation where two or more threads access an unprotected shared resource or when the threads' executions behave differently, depending on the timing and the underlying process architecture.
A deadlock condition happens when two or more threads have a circular dependency on each other to access a resource.
The general recommendations when writing some code that may be executed from multiple threads are as follows:
- Avoid shared resources as much as possible...