Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When implementing a thread safe queue or list, is it required to lock before returning Count?

When implementing a thread safe list or queue; does it require to lock on the List.Count property before returning the Count i.e:

//...
public int Count 
{
    lock (_syncObject)
    {
       return _list.Count;
    }
}
//...

Is it necessary to do a lock because of the original _list.Count variable maybe not a volatile variable?

like image 907
Jalal Said Avatar asked Jan 22 '23 05:01

Jalal Said


1 Answers

Yes, that is necessary, but mostly irrelevant. Without the lock you could be reading stale values or even, depending on the inner working and the type of _list.Count, introduce errors.

But note that using that Count property is problematic, any calling code cannot really rely on it:

if (myStore.Count > 0)  // this Count's getter  locks internally 
{
    var item = myStore.Dequeue(); // not safe, myStore could be empty
}

So you should aim for a design where checking the Count and acting on it are combined:

ItemType GetNullOrFirst()
{
    lock (_syncObject)
    {
       if (_list.Count > 0)
       {
           ....
       }
    }
}

Additional:

is it nessesary to do a lock because of the original _list.Count variable maybe not a volatile variable?

The _list.Count is not a variable but a property. It cannot be marked volatile. Whether it is thread-safe depends on the getter code of the property, but it will usually be safe. But unreliable.

like image 167
Henk Holterman Avatar answered Jan 23 '23 18:01

Henk Holterman