Permalink
Browse files

bqueue: some microoptimizations

  • Loading branch information...
1 parent 0f9849e commit 556fbaaf13d04e0563d7ce7b104c9009b7df4ee9 @esmil esmil committed Jan 23, 2012
Showing with 10 additions and 9 deletions.
  1. +10 −9 bqueue.lua
View
@@ -13,38 +13,39 @@
-- put x into the queue, this always succeeds immediately
--
-- r, err = queue:get(timeout)
--- returns the first element put in the queue or suspends the
--- current current coroutine until there is an element in the queue
+-- 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 newsleeper = utils.sleeper
local remove = table.remove
local BQueue = {}
BQueue.__index = BQueue
function BQueue:put(x)
- local sleeper = self.sleeper
- if sleeper:wakeup(x) then return end
+ if self.sleeper:wakeup(x) then return end
local n = self.n + 1
self[n] = x
self.n = n
end
-function BQueue:get(n)
- if self.n == 0 then
- return self.sleeper:sleep(n)
+function BQueue:get(timeout)
+ local n = self.n
+ if n == 0 then
+ return self.sleeper:sleep(timeout)
end
- self.n = self.n - 1
+ self.n = n - 1
return remove(self, 1)
end
+local setmetatable, newsleeper = setmetatable, utils.sleeper
+
local function new()
return setmetatable({
sleeper = newsleeper(),

0 comments on commit 556fbaa

Please sign in to comment.