Search code examples
multithreadingconcurrencythread-safetyrace-conditionthread-synchronization

I do not understand why it is necessary to protect a single-instruction setter with a mutex


I have a source code that does something like this:

void setX(int x) {
  pthread_mutex_lock(m_lock);
  m_x = x;
  pthread_mutex_unlock(m_lock);
}

This method is executed by several threads concurrently.

I have read that it is necessary to protect it with mutex to make it thread-safe, but I do not understand why is this necessary.

As far as I understand, since the method executes only one instruction, it will be always atomic (thread-safe) regardless you use a mutex or not.

So, my question is: is there any way through which the above method, without mutexes, can generate a race condition?


Solution

  • This depends on context. In probably most languages/systems, assigning an int value to a field is an atomic operation.

    But theoretically, that isn't guaranteed. If you had a system only able to deal with 8 bit bytes assigning a 2 or 4 byte int value would not be atomic!

    And as soon as you change the type of the variable/field from int to say long, all bets are off anyway. In that sense, the above code is simply overly "conservative". But it has one advantage: in case you ever decide to change the type of that field/parameter to something that can't be assigned atomically - no further changes are required.

    Thus: you are correct - using a mutex isn't required here. But it doesn't hurt either (maybe except things as allowing for dead locks or performance impacts due to adding the need to acquire a lock).