Skip to content

Instantly share code, notes, and snippets.

@Multihuntr
Created October 20, 2017 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Multihuntr/af0bc9bcc446d0da09685669e80ac3b2 to your computer and use it in GitHub Desktop.
Save Multihuntr/af0bc9bcc446d0da09685669e80ac3b2 to your computer and use it in GitHub Desktop.
Blocking Thread-safe Random Queue
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)
@Multihuntr
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment