Created
October 20, 2017 07:55
-
-
Save Multihuntr/af0bc9bcc446d0da09685669e80ac3b2 to your computer and use it in GitHub Desktop.
Blocking Thread-safe Random Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import queue | |
import random | |
class RandomQueue(queue.Queue): | |
def _put(self, item): | |
n = len(self.queue) | |
i = random.randint(0, n) | |
self.queue.insert(i, item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the implementation of python's queue.Queue, they wrap the _put() and _get() methods with all of the mutex's, locks and conditions, in put() and get(), respectively.
Now you can use RandomQueue exactly as you would a normal queue.Queue, except, RandomQueue RandomQueue.get() returns a random element of the queue.