I need to implement a producer/consumer bounded queue, multiple consumers against a single producer.
I have a push function that adds an item to the queue and then checks for maxsize. If we have reached it return false, in every other case return true.
In the following code _vector is a List<T>, onSignal basically consumes an item in an asynchronous way.
Do you see issues with this code?
public bool Push(T message)
{
bool canEnqueue = true;
lock (_vector)
{
_vector.Add(message);
if (_vector.Count >= _maxSize)
{
canEnqueue = false;
}
}
var onSignal = SignalEvent;
if (onSignal != null)
{
onSignal();
}
return canEnqueue;
}
I know you said single-producer, multiple-consumer, but it’s worth mentioning anyway: if your queue is almost full (say 24 out of 25 slots), then if two threads
Pushat the same time, you will end up exceeding the limit. If there’s even a chance you might have multiple producers at some point in the future, you should consider makingPusha blocking call, and have it wait for an “available”AutoResetEventwhich is signaled after either an item is dequeued or after an item is enqueued while there are still slots available.The only other potential issue I see is the
SignalEvent. You don’t show us the implementation of that. If it’s declared aspublic event SignalEventDelegate SignalEvent, then you will be OK because the compiler automatically adds aSynchronizedAttribute. However, ifSignalEventuses a backing delegate withadd/removesyntax, then you will need to provide your own locking for the event itself, otherwise it will be possible for a consumer to detach from the event just a little too late and still receive a couple of signals afterward.Edit: Actually, that is possible regardless; more importantly, if you’ve used a property-style add/remove delegate without the appropriate locking, it is actually possible for the delegate to be in an invalid state when you try to execute it. Even with a synchronized event, consumers need to be prepared to receive (and discard) notifications after they’ve unsubscribed.
Other than that I see no issues – although that doesn’t mean that there aren’t any, it just means I haven’t noticed any.