Multithreading with threadsafe using simple lock object

we will use a simple console app to demonstrate thread safe in multiple threading using lock object to prevent race condition. race condition could occur when more than one thread access the shared resource at the same time. For example below we have a bank account class that can be deposit amount of money to shared field balance.

We need to protect it to prevent race conditions, where two or more threads update it simultaneously. For example, without thread safety, if thread #1 and thread #2 both try to deposit $50 at the same time, they might both read the initial balance as $0 and each set it to $50. In this case, we “lose” $50 because we expected the balance to be $100.
This is why it’s important to protect shared resources accessed by multiple threads.
Using a lock ensures that only one thread can access the resource at a time.
Once a thread finishes updating, it releases the lock so another thread can safely access the resource.

Our main program running on the main thread instantiate the MyBankABC object and then kick off 2 workers threads t1 and t2 doing the deposit 50 at the same time. Since we protect our balance field with lock object ensuring only one thread can update this field so at the end we call assert to make sure that our balance is 100.

Complete console app: https://tinyurl.com/389b3kdp

Leave a Reply

Your email address will not be published. Required fields are marked *