Skip to content

Instantly share code, notes, and snippets.

@sonya75
Last active June 13, 2017 02:17
Show Gist options
  • Save sonya75/16124b46917ca105686763e05459ddf5 to your computer and use it in GitHub Desktop.
Save sonya75/16124b46917ca105686763e05459ddf5 to your computer and use it in GitHub Desktop.
import Queue
import thread
from threading import Lock
class ThreadPriorityQueue:
"""A Queue like class where in the get function the thread
with lowest thread id from where get is being called gets priority.
Not the one who called get first"""
def __init__(self):
self.dataqueue=Queue.Queue()
self.itemlock=Lock()
self.requestqueue=Queue.PriorityQueue()
def put(self,item):
self.itemlock.acquire()
while True:
try:
id,q=self.requestqueue.get_nowait()
q.put_nowait(item)
break
except Queue.Empty:
self.dataqueue.put(item)
break
except:
pass
self.itemlock.release()
def get(self,timeout=None):
self.itemlock.acquire()
try:
v=self.dataqueue.get_nowait()
self.itemlock.release()
return v
except:
pass
v=Queue.Queue(1)
self.requestqueue.put((thread.get_ident(),v))
self.itemlock.release()
try:
m=v.get(timeout=timeout)
return m
except:
try:
v.put_nowait(1)
except Queue.Full:
return v.get_nowait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment