Consider the following code that runs in thread B (that's all that runs in that thread):
private void KeepValueCurrent(WaitHandle mre)
{
while (mre.WaitOne(50))
{
var newAddressOffset = LengthOfLastLogEntry;
if (newAddressOffset > _currentAddressOffset)
{
//Only update if new value is larger than existing
lock(_locker) {_currentAddressOffset = newAddressOffset;}
}
}
}
Will I be able to access _currentAddressOffset
in thread A, like below, or will the lock block me because the loop in thread B runs so fast? My program has so many other dependencies, so I have not been able to test it by itself.
lock (_locker) { currentAddressOffset = _currentAddressOffset; }
Note: The _currentAddressOffset
is a global int variable, with modifier volatile
to avoid any compiler optimization.
UPDATE: Follow-On Question
From the received answers it has become apparent that I do not need to lock around the int if the only place I write to _currentAddressOffset
is in the loop in thread B. What if, however, in thread A I also write to that variable. Then the concept of race conditions comes up, and I will change my while loop in thread B, to this:
private void KeepValueCurrent(WaitHandle mre)
{
while (mre.WaitOne(50))
{
var newAddressOffset = LengthOfLastLogEntry;
lock(_locker)
{
if (newAddressOffset > _currentAddressOffset)
{
//Only update if new value is larger than existing
_currentAddressOffset = newAddressOffset;
}
}
}
}
In thread A, I will now read and write to it like this:
lock (_locker) { currentAddressOffset = _currentAddressOffset; } //Read
lock (_locker) { _currentAddressOffset = newValue; } //Write
Are the locks needed in this scenario, to avoid race conditions?
Thanks a lot.