summaryrefslogtreecommitdiff
path: root/queue.lua
blob: 0836ff1f50109dd032c16fb25e1deb419529dcb7 (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
40
41
42
43
local cqueues = require'cqueues'
local condition = require'cqueues.condition'
local cqaux = require'cqueues.auxlib'
local class = require 'r.class'

local Queue = class()

function Queue.make(cls)
	return setmetatable({
		items = {},
		cv = condition.new(),
	}, cls) end

function Queue.enqueue(self, ...)
	local item = table.pack(...)
	print('q',...)
	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
					(function(...)
						print('p',...)
						coroutine.yield(...)
					end)(table.unpack(item, 1, item.n))
				end
			end
			self.cv:wait()
		end
	end)
end


return Queue