Skip to content

Commit

Permalink
Merge pull request luvit#199 from daurnimator/improve-cqueues-examples
Browse files Browse the repository at this point in the history
Improve cqueues exampels
  • Loading branch information
creationix committed Nov 30, 2015
2 parents 85ccc04 + 127f72e commit b5562cd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion examples/cqueues-main.lua
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ cq:wrap(function()
end
end)

uv.timer_start(uv.new_timer(), 1000, 1000, function()
uv.new_timer():start(1000, 1000, function()
print("HELLO FROM LUV")
end)

Expand Down
19 changes: 18 additions & 1 deletion examples/cqueues-slave.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
--[[
Demonstrates using cqueues with a luv mainloop
Starts a simple sleep+print loop using each library's native form.
They should print intertwined.
]]

local cqueues = require "cqueues"
Expand All @@ -12,27 +15,41 @@ do
local function reset_timer()
local timeout = cq:timeout()
if timeout then
timer:set_repeat(timeout * 1000)
-- libuv takes milliseconds as an integer,
-- while cqueues gives timeouts as a floating point number
-- use `math.ceil` as we'd rather wake up late than early
timer:set_repeat(math.ceil(timeout * 1000))
timer:again()
else
-- stop timer for now; it may be restarted later.
timer:stop()
end
end
local function onready()
-- Step the cqueues loop once (sleeping for max 0 seconds)
assert(cq:step(0))
reset_timer()
end
-- Need to call `start` on libuv timer now
-- to provide callback and so that `again` works
timer:start(0, 0, onready)
-- Ask libuv to watch the cqueue pollfd
uv.new_poll(cq:pollfd()):start(cq:events(), onready)
end

-- Adds a new function to the scheduler `cq`
-- The functions is an infinite loop that sleeps for 1 second and prints
cq:wrap(function()
while true do
cqueues.sleep(1)
print("HELLO FROM CQUEUES")
end
end)

-- Start a luv timer that fires every 1 second
uv.new_timer():start(1000, 1000, function()
print("HELLO FROM LUV")
end)

-- Run luv mainloop
uv.run()

0 comments on commit b5562cd

Please sign in to comment.