-
Notifications
You must be signed in to change notification settings - Fork 2
/
bqueue.lua
61 lines (50 loc) · 1.1 KB
/
bqueue.lua
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
--
-- A "blocking queue" for the Lua Event Machine
--
-- Usage:
--
-- bqueue = require 'bqueue'
-- load the module
--
-- queue = bqueue.new()
-- create a new queue
--
-- queue:put(x)
-- put x into the queue, this always succeeds immediately
--
-- r, err = queue:get(timeout)
-- returns the first element in the queue or suspends the
-- current current coroutine until an element is put on the queue
-- if timeout is non-nil it shall return nil, 'timeout' if nothing is
-- put on the queue within timeout seconds
--
local utils = require 'lem.utils'
local remove = table.remove
local BQueue = {}
BQueue.__index = BQueue
function BQueue:put(x)
if self.sleeper:wakeup(x) then return end
local n = self.n + 1
self[n] = x
self.n = n
end
function BQueue:get(timeout)
local n = self.n
if n == 0 then
return self.sleeper:sleep(timeout)
end
self.n = n - 1
return remove(self, 1)
end
local setmetatable, newsleeper = setmetatable, utils.newsleeper
local function new()
return setmetatable({
sleeper = newsleeper(),
n = 0,
}, BQueue)
end
return {
BQueue = BQueue,
new = new,
}
-- vim: set ts=2 sw=2 noet: