Is there a simple way to do async in Perl? I have the following logic for an Apache app:
get request
process request
write to log
return
what I want to do is to have the "write to log" part to be async, so that I can do the "return" part asap.
Perl can do asynchronous programming with modules like IO::Async or Coro, but it's single threaded. You can compile Perl with threads, which provide multi-threaded computing.
Here's an example: Data may take long a long time to submit to a database. With asynchronous programming, the user can move to another screen while the function continues to execute. When a photo is loaded and sent on Instagram, the user does not have to stay on the same screen waiting for the photo to finish loading.
Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished.
Unfortunately, this typically entails the POE framework, but there is also a growing alternative (which I would want to try first) called AnyEvent.
See this question for learning materials for more information about learning POE. POE is a framework and it tends to eat your whole application. It also doesn't look like Perl, and sticks out. I believe it is a big learning curve for your typical application.
AnyEvent is simple continuation based asyncronous tasking, you should be able to figure it out fairly well with just the CPAN docs.
For your specific question you would use AnyEvent's AIO or POE's Read Write wheel
Consider looking at Coro.
From its CPAN documentation:
Unlike the so-called "Perl threads" (which are not actually real threads but only the windows process emulation (see section of same name for more details) ported to unix, and as such act as processes), Coro provides a full shared address space, which makes communication between threads very easy. And Coro's threads are fast, too: disabling the Windows process emulation code in your perl and using Coro can easily result in a two to four times speed increase for your programs. A parallel matrix multiplication benchmark runs over 300 times faster on a single core than perl's pseudo-threads on a quad core using all four cores.
This includes Coro::AIO
, a "truly asynchronous file and directory I/O", which might be what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With