What is wrong with the code : x = x + a , in context of a concurrent system?

  • 0

    How can you implement the same for a concurrent system?

  • 9
    1. At machine level, x = x + a is implemented in multiple instructions :
      a. Load the value of x into register.
      b. Add a to the register value.
      c. Store the value from register.

    For concurrent systems, race condition can come and result in multiple processes/threads reading the old value simultaneously and updating independently. This will result in overwriting results from each other.

    1. To implement the code safely, we need to acquire write-lock (mutually exclusive lock) before writing our value. This will result in updating of value sequentially which will avoid the race condition.

    Example pseudo code can be :

    void add(x, a) {
            x = x + a;

    This atomic operation is also called as FetchAndAdd.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.