vr has asked for the wisdom of the Perl Monks concerning the following question:

Here they say about web server embedding into foreign event loop. The last line in code example is blocking, isn't it? Do they mean, I follow further link to "one_tick" in Mojo::IOLoop and add a sub-second timer? So that either real event or this timer occur? But most of the time, it will block the "foreign event loop" for 0.5 sec, correct? Is there non-blocking way to check for Mojolicious events?

And this happens in a callback of e.g. IO::Async::Timer::Periodic with e.g. 2 seconds interval, correct? If all this is so, it's ugly as hell.

I know about IO::Async::Loop::Mojo, but it seems to be unhappy about Windows.

P.S. Or did I misinterpret it completely and they mean running 2 event loops in parallel?

Replies are listed 'Best First'.
Re: "Web server embedding" (Mojolicious docs)
by Corion (Patriarch) on May 11, 2017 at 12:59 UTC

    There are two approaches to running two event loops in parallel.

    The approach you already outlined is to set up a "timer" and periodically run the "other" event loop. This gets you the advantage of running single-threaded, without race conditions at the price of high constant CPU load.

    The other one is to run each event loop in its own thread, which brings you the advantage and disadvantage that both event loops run in parallel. You get all the advantages of near-time event processing coupled with all the disadvantages of threads, like race conditions etc.

    If you are lucky you can make the secondary event loop write to a socket that the primary event loop listens on. This way, you can channel all the events from the secondary event loop to the primary event loop.

      Thanks. Just placing code from the very first link in OP to a separate thread (e.g. with IO::Async::Routine) gave me nothing, because Mojo::IOLoop-> one_tick blocks again, and Routine won't accept commands from 'main' loop. So, a Mojo::IOLoop::Stream (?) must be added to Mojo's loop for communication. For which I need some time to figure it all out. Or, otherwise, ugly timers, be it separate thread or not.

      OTOH, staying within IO::Async (Net::Async) namespaces, the Net::Async::HTTP::Server and Net::Async::WebSocket::Server solved, partly, what this all was about, with a single event loop. Just partly.

      Closing browser (hence Websocket connection) leads to instantaneous on_close and "WebSocket closed with status 1001" using simple Mojolicious application. But in "pure" IO:Async (Net::Async) app I get on_frame event with WebSocket frame being 2 characters "\x{03}\x{fffd}". What does it mean, how to parse it? Does it have to (and will it) be so low level all the way ahead?

      On still another hand, I just wanted to experiment with Mojolicious, use it within existing IO:Async app. Sorry for this rant :)