Search code examples
qtembedlibuv

libuv event loop in qt


Is there a way without using multiple threads?

I found this https://stackoverflow.com/a/17329626/4014896

But i don't get how it works. Shouldn't it cause 100% CPU usage in the example? and how can I embed it, for example, into QT?

there is also this: https://github.com/svalaskevicius/qt-event-dispatcher-libuv But there is no documentation at all. But from my looks it seems to be something that translates from example QSocket to uv_tcp_socket which is not what I'm searching for.


Solution

  • In short - you'll either need to merge the two event loops or use separate threads and sync the event handlers manually..

    The first link you pasted shows how to process libuv events that have happened since the last invocation. The while stated there will use ~100% CPU if there are no events dispatched (as it will just keep polling).

    The second link (qt-event-dispatcher-libuv) is a project I've created to tackle the same problem. It does, however, work as you described - by using libuv to handle Qt's event loop (and by doing that - merges the two event loops into one).

    To use it you'd just need to register the event dispatcher in your application using http://qt-project.org/doc/qt-5/qcoreapplication.html#setEventDispatcher. An example where this library is used - https://github.com/svalaskevicius/qtjs-generator/blob/master/src/runner/main.cpp#L179

    There is still one catch using this approach - while it works very well on linux, there are some problems on OS X as the Qt's Cocoa platform support plugin handles some Cocoa's event loop operations and doesn't provide a nice API to merge it as well (currently its updating them one its freed up after a small timeout so there is some (barely?) noticeable lag to handle the GUI events) - I was planning to port the platform support plugin to be able to integrate it as well but that's still in future. And I haven't tested it on windows yet :)

    An alternative solution could probably be to try to merge the two loops from another direction that I've done - instead of making Qt to use libuv, libuv's api could be provided that uses Qt's handlers - although it requires a considerable amount of work as well.

    Please let me know if there is any more info I could provide.

    Regards,