I've been facing a few race conditions in my code lately and I'm wondering if secondary/tertiary locks actually add any value. They seem very redundant, and this SO post seems to align with my thought process on it by stating:
In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:
obtain lock for x
...release lock for x
Given this simple example to remove empty queues from a collection:
Dictionary<Guid, Queue<int>> _queues = new Dictionary<Guid, Queue<int>>();
...
lock (_queues) {
while (_queues.Any(a => a.Value.Count == 0)) {
Guid id = _queues.First(f => f.Value.Count == 0);
if (_queues.ContainsKey(id))
lock (_queues)
_queues.Remove(id);
}
}
Does the second lock provide any value?