leonbloy
leonbloy

Reputation: 75896

threads in Dancer

I'm using Dancer 1.31, in a standard configuration (plackup/Starman).

In a request I wished to call a perl function asynchronously, so that the request returns inmmediately. Think of the typical "long running operation" scenario, in which one wants to return a "processing page" with a refresh+redirect.

I (naively?) tried with a thread:

sub myfunc {  
   sleep 9; # just for testing a slow operation
}

any '/test1' => sub {
   my $thr = threads->create('myfunc'); 
   $thr->detach();
   return "done" ;
};

I does not work, the server seems to freeze, and the error log does not show anything. I guess manual creation of threads are forbidden inside Dancer? It's an issue with PSGI? Which is the recommended way?

Upvotes: 1

Views: 758

Answers (2)

Yanick
Yanick

Reputation: 1280

Threads are definitively iffy with Perl. It might be possible to write some threaded Dancer code, but to be honest I don't think we ever tried it. And considering that Dancer 1's core use simpleton classes, it might also be very tricky.

As Ogla says, there are other ways to implement asynchronous behavior in Dancer. You say that you are using Starman, which is a forking engine. But there is also Twiggy, which is AnyEvent-based. To see how to leverage it to write asynchronous code, have a gander at Dancer::Plugin::Async.

Upvotes: 1

Ogla V. Sungutay
Ogla V. Sungutay

Reputation: 161

I would stay away from perl threads especially in a web server environment. It will most likely crash your server when you join or detach them.

I usually create a few threads (thread pool) BEFORE initializing other modules and keep them around for the entire life time of the application. Thread::Queue nicely provides communication between the workers and the main thread.

The best asynchronous solution I find in Perl is POE. In Linux I prefer using POE::Wheel::Run to run executables and subroutines asynchronously. It uses fork and has a beautiful interface allowing communication with the child process. (In Windows it's not usable due to thread dependency)

Setting up Dancer and POE inside the same application/script may cause problems and POE's event loop may be blocked. A single worker thread dedicated to POE may come handy, or I would write another server based on POE and just communicate with the Dancer application via sockets.

Upvotes: 1

Related Questions