Skip to content

Instantly share code, notes, and snippets.

@daurnimator
Created June 24, 2015 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daurnimator/11e356b98b7baefae10a to your computer and use it in GitHub Desktop.
Save daurnimator/11e356b98b7baefae10a to your computer and use it in GitHub Desktop.
Example of using cqueues inside of a glib mainloop
-- Example of using cqueues inside of a glib mainloop
-- https://github.com/pavouk/lgi/issues/111
local cqueues = require "cqueues"
local lgi = require "lgi"
local GLib = lgi.GLib
local map = {}
local function source_to_cq(source)
return map[source].cq
end
local source_funcs = GLib.SourceFuncs()
function source_funcs:prepare()
local cq = source_to_cq(self)
local timeout = cq:timeout()
if cq:empty() then
return false, -1
elseif timeout == 0 then
return true, 0
else
return false, timeout*1000
end
end
function source_funcs:dispatch(_ignored_cbk)
local cq = source_to_cq(self)
local ok, err, errno, thread = cq:step(0)
if not ok then
error(debug.traceback(thread, err), 0)
end
return cq:count() > 0 -- true indicates that more events can happen
end
function source_funcs:finalize()
map[self] = nil
end
local function add_cq_source(main_context, cq)
local fd = GLib.PollFD()
fd.fd = cq:pollfd()
fd.events = 1 -- pollin
local source = GLib.Source(source_funcs, GLib.Source._size)
source:add_poll(fd)
source:attach(main_context)
map[source] = {
cq = cq;
PollFD = fd; -- need to hang onto PollFD
}
return source
end
-- create a cqueues thread
local cq = cqueues.new()
cq:wrap(function()
for i=1,5 do
print("hi")
cqueues.sleep(1)
end
end)
print("STARTING")
local main_loop = GLib.MainLoop()
add_cq_source(main_loop:get_context(), cq)
main_loop:run()
print("DONE")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment