2019-04-05 05:05:53 +08:00
|
|
|
import asyncio
|
|
|
|
|
|
|
|
"""
|
|
|
|
NOTE: ISSUE IS THAT THERE task IS BLOCKING SINCE IT IS WAITING ON SAME COROUTINE THAT
|
|
|
|
WE ARE RUNNING ON
|
|
|
|
"""
|
|
|
|
class OrderedQueue():
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.last_gotten_seqno = 0
|
|
|
|
self.queue = asyncio.PriorityQueue()
|
|
|
|
self.task = None
|
|
|
|
|
|
|
|
async def put(self, item):
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("Put " + str(item))
|
2019-04-05 05:05:53 +08:00
|
|
|
seqno = item[0]
|
|
|
|
await self.queue.put(item)
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("Added to queue " + str(item))
|
2019-04-05 05:05:53 +08:00
|
|
|
if self.last_gotten_seqno + 1 == seqno and self.task is not None:
|
|
|
|
# Allow get future to return the most recent item that is put
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("Set called")
|
2019-04-05 05:05:53 +08:00
|
|
|
self.task.set()
|
|
|
|
|
|
|
|
async def get(self):
|
|
|
|
if self.queue.qsize() > 0:
|
|
|
|
front_item = await self.queue.get()
|
|
|
|
|
|
|
|
if front_item[0] == self.last_gotten_seqno + 1:
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("Trivial get " + str(front_item))
|
2019-04-05 05:05:53 +08:00
|
|
|
self.last_gotten_seqno += 1
|
|
|
|
return front_item
|
|
|
|
else:
|
|
|
|
# Put element back as it should not be delivered yet
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("Front item put back 1")
|
|
|
|
# print(str(self.last_gotten_seqno))
|
|
|
|
# print(front_item[1])
|
2019-04-05 05:05:53 +08:00
|
|
|
await self.queue.put(front_item)
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("Front item put back 2")
|
2019-04-05 05:05:53 +08:00
|
|
|
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("get 2")
|
2019-04-05 05:05:53 +08:00
|
|
|
# Wait until
|
|
|
|
self.task = asyncio.Event()
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("get 3")
|
2019-04-05 05:05:53 +08:00
|
|
|
await self.task.wait()
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("get 4")
|
2019-04-05 05:05:53 +08:00
|
|
|
item = await self.queue.get()
|
2019-04-05 05:40:29 +08:00
|
|
|
# print("get 5")
|
2019-04-05 05:05:53 +08:00
|
|
|
# print(str(item) + " got from queue")
|
|
|
|
|
|
|
|
# Remove task
|
|
|
|
self.task = None
|
|
|
|
|
|
|
|
self.last_gotten_seqno += 1
|
|
|
|
|
|
|
|
return item
|