Importance of Thread Synchronization

Consider that there is a program that is being used for managing the banking data. Now, assume that two threads are being used for credit and debit in a bank account. Now, assume the following sequence of transactions of a user:

  1. Initial Balance = 300
  2. Credited_process: 400, Current Balance = 700
  3. Debited_process: 500, Current Balance = 200

Now, assume that there is no synchronization between the processes running on the different threads. So, it is possible that the sequence of the operation can be:

  1. Initial Balance: 300
  2. Debited_process: 500, Current Balance = 300
  3. Credit_process: 400, Current Balance = 700

Due to this change in the sequence, the user wont be able to withdraw his/her money from the bank account even though he had credited enough money in the account. Here, both credit_process and debit_process threads can be synchronized so that when there is a simultaneous credit and debit requests, it should first execute the credit request.

There can be many such concurrency issues that arises due to non-synchronized operations. Some of them are:

Thread Synchronization in C++

In C++ multithreading, synchronization between multiple threads is necessary for the smooth, predictable, and reliable execution of the program. It allows the multiple threads to work together in conjunction by having a proper way of communication between them. If we do not synchronize the threads working on a shared resource properly, it may cause some of the concurrency problems.

Similar Reads

Importance of Thread Synchronization

Consider that there is a program that is being used for managing the banking data. Now, assume that two threads are being used for credit and debit in a bank account. Now, assume the following sequence of transactions of a user:...

Thread Synchronization in C++

In C++, thread synchronization is possible using the following methods:...

Conclusion

...