Closed poor1017 closed 1 year ago
Sounds like you want to use a semaphore in front of the queue. A LightweightSemaphore
is included in this library.
@cameron314
Thank you for your suggestion. I think I can implement like this:
size_approx()
every time they get a UUID;size_approx
is lower than the low water mark, then sema->signal()
is called in consumer thread to notify the producer to continue producing UUIDs;size_approx
is greater than the high water mark?size_approx
every time they get a UUID. Will the performance be greatly affected?Looking forward to your reply.
Don't use size_approx, you'll have races.
Set the semaphore to the maximum number of items. Before the producer enqueues, wait on the semaphore. After a consumer dequeues, signal the semaphore.
There will be some overhead, but not much. LightweigthSemaphore is designed to be very efficient in the hot path when no blocking is actually necessary.
Hi @cameron314
Is this a dead-lock?
I don't understand. Why would the queue stay empty? The first N waits on the semaphore would return immediately.
Also, signaling a semaphore is not a blocking operation.
@cameron314
Before the producer enqueues, wait on the semaphore.
The queue is empty at beginning, and the semaphore will never get signal.
After a consumer dequeues, signal the semaphore.
Because the queue is always empty, so dequeuing is blocking, so signaling operation can not be excuted.
The semaphore would be initialized to some value larger than 0.
@cameron314
Your solution works very well, thank you!
Hi @cameron314
Thank you for your greate library!
I have a concurrent queue, the producer will generate UUID then enqueue, several consumers will take UUID from the queue. My requirement is: if the queue has enough UUIDs (we can call this as high water level) in it, it will block enqueue, until its UUIDs is lower than a number (we can call this low water level).
If high/low water level is too complex, what about a threshold?
Looking forward to your reply.