summaryrefslogtreecommitdiff
path: root/queue.lua
blob: 8c9c373c2b7c5f4112defa64ac8815ca58b15992 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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