diff options
Diffstat (limited to 'util/queue.lua')
-rw-r--r-- | util/queue.lua | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/util/queue.lua b/util/queue.lua new file mode 100644 index 0000000..8c9c373 --- /dev/null +++ b/util/queue.lua @@ -0,0 +1,39 @@ +local cqueues = require'cqueues' +local condition = require'cqueues.condition' +local cqaux = require'cqueues.auxlib' + +local Queue = {} + +function Queue.make() + return setmetatable({ + items = {}, + cv = condition.new(), + }, {__index=Queue}) +end + +function Queue.enqueue(self, ...) + local item = table.pack(...) + table.insert(self.items, item) + if #self.items > 128 then + print('warning: queue is quite big') + end + self.cv:signal() +end + +function Queue.iter(self) + return cqaux.wrap(function() + while true do + while #self.items > 0 do + local items = self.items + self.items = {} -- the old switcheroo + for _, item in ipairs(items) do + coroutine.yield(table.unpack(item, 1, item.n)) + end + end + self.cv:wait() + end + end) +end + + +return Queue |