user has an initial balance of 30. An amount of 100 is being transferred simultaneously to the user by each of the thread. 1. Thread 1 reads the current balance (30) 2. Thread 1 updates the current balance (130) 3. Before thread 1 saves to the database, thread 2 reads the value of A (gets 30) 4. Thread 2 updates balance as 130. 5. Thread 2 writes value of 130 to DB; thread 1 also does the same. The problem is that, a read is allowed midway of another modify operation.
data & has non-atomic operations - Threads share memory location of parent process - No problem if no data is shared - No problem if code executed with threads is immutable and atomic
- prints the value, Then prints separator and end (by default \n) • It is thread unsafe because the operation is non atomic • Context switch can happen in between
that allows only one thread to access a resource at a time. Practical Use-Case: Ensuring that only one thread can modify a shared variable at a time to prevent race conditions.
that allows the same thread to acquire the lock multiple times without causing a deadlock. Practical Use-Case: Allowing a thread to re-enter a critical section of code that it already holds the lock for, such as in recursive functions.
that controls access to a resource by maintaining a counter, allowing a set number of threads to access the resource simultaneously. Practical Use-Case: Limiting the number of concurrent connections to a database to prevent overload. (eg: connection pooling)
that allows one thread to signal one or more other threads that a particular condition has been met. Practical Use-Case: Notifying worker threads that new data is available for processing.
that allows threads to wait for certain conditions to be met before continuing execution. Practical Use-Case: Pausing a thread until a specific condition is met, such as waiting for a queue to be non-empty before consuming an item.
that allows multiple threads to wait until all threads have reached a certain point before any of them can proceed. Practical Use-Case: Ensuring that all worker threads complete their individual tasks before any thread proceeds to the next phase of a multi-phase computation.
here (using Python locks) is not suitable for production. - Multiple instances of our Python app can be deployed across regions. - Enable locks at the source of truth level. - Enable locks at the database level
the code you are working with might not be designed for thread safety - even library code. - Before switching to multithreading, check for shared mutable data & atomicity requirements. - Add synchronization primitives to enforce thread-safety. “When in doubt, use a mutex!” - CPython docs ( https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe )