Skip to content

Instantly share code, notes, and snippets.

@sonya75
Created August 2, 2017 03:20
Show Gist options
  • Save sonya75/00679d8a47f6973b4b0f929f0a3d1363 to your computer and use it in GitHub Desktop.
Save sonya75/00679d8a47f6973b4b0f929f0a3d1363 to your computer and use it in GitHub Desktop.
from threading import Lock, Condition
import _thread
import Queue
import time
class ThreadedQueue:
def __init__(self):
self.items = []
self.globallock = Lock()
self.globalcond = Condition(self.globallock)
def get(self, wait=-1):
starttime = time.time()
id = _thread.get_ident()
v = self.items
with self.globallock:
for i in range(0, len(v)):
u = v[i]
if id == u[0]:
del v[i]
return u[1]
while True:
v = time.time() - starttime
if (v >= wait) & (wait >= 0):
raise Queue.Empty
if wait >= 0:
self.globalcond.wait(wait - v)
else:
self.globalcond.wait()
if len(self.items) == 0:
continue
w = self.items[-1]
if w[0] == id:
return w[1]
def get_nowait(self):
return self.get(0)
def put(self, item, threadid):
with self.globallock:
self.items.append((threadid, item))
self.globalcond.notifyAll()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment