0

Inside a function, I am calling another function(changeValue) that has a mutex lock on the global variables it modifies. changeValue is also periodically called by other functions.

changeValue locks the mutex, changes sum, and then unlocks mutex.

changeValue is of void type, so it simply modifies the global variable sum(e.g. sum = 10). After my call to changeValue(), I want to do some calculations using the global variables modified by changeValue().

Will sum still be equal to 10 after my call to changeValue()?

Smiley7
  • 185
  • 1
  • 3
  • 10

1 Answers1

2

Since the lock is active inside the changeValue function only, everything might change between function invocations. The values are consistent only while the mutex is held. If you need the values calculated in one specific invocation outside the changeValue function, you need to assign them to reference parameters while the lock is still active:

void changeValue (int* iValue1, int* iValue2)
    {
    // acquire the mutex, compute values, assign iValue1 and iValue2, release the mutex
    return;
    }

So you're copying the required values while they are consistent, and work on them quietly, while other threads might update them in turn.

SBS
  • 806
  • 5
  • 13