I have an interesting producer-consumer spin-off to implement and I cannot wrap my head around its algorithm. So, every producer will "produce" numbers between the given range (min, max) which give the same reminder to the division by the given "quotient". Same goes for the consumer.
Extra requirement: finite buffer.
My thoughts on this:
My problems:
I was thinking about using an array list for the "buffer" and every consumer would perform a lock-free lookup for a "compatible" element to consume, removing an element if one available or trying again if none available. I think this would be inefficient because of wasted CPU cycles on "tries".
PS: I am using java for this, but pseudo-code is really good as well.
Thanks in advance!
To be sure that producer produces all numbers from given range that have the same remainder you can use the following pseudo-code
int current = start;
while (current++ <= end) { //assuming your ranges are inclusive
if (current % quotient == 0) {
publish(current);
}
}
To support partitioning you basically need some kind of Map<YourKey, Queue>
. Each producer and consumer will be associated with a key and producer will publish to the queue associated with his key and consumer will consume from a queue associated with its key. You can use your range as a key for a queue.