Globals and Threads in Mojolicious for handling different paths
Asked Answered
T

1

6

In my Mojolicious perl code I handle a jobs created and watched from a remote client.

I keep the jobs in a array of hashes, which is a global variable.

It is then used in handlers of PUT '/job/create' and GET '/job/status'. When adding a new job with the PUT '/job/create' the array gets extended in the subroutine (it contains 4 elements in the code below), but when requesting the jobs' status via GET '/job/status' the list of jobs, the array does not contain the added elements (it counts 2 elements).

Thanks, Jan

Here is the code:

#!/usr/bin/perl -w

use threads; 
use threads::shared; 
use Mojolicious::Lite; 
use Mojo::JSON; 
my (%record, %job1, %job2, %job3, @jobs) : shared; 

%job1 = ( id=>"id1"); 
%job2 = ( id=>"id2"); 
%job3 = ( id=>"id3"); 

push ( @jobs, \%job1 ); 
push ( @jobs, \%job2 ); 

app->config(hypnotoad => {listen => ['http://*:3000']}); 

put '/job/create' => sub { 
    my $self = shift; 
    my $obj = Mojo::JSON->decode( $self->req->body ); 
    my $id = $obj->{id}; 
    %record = (id => $id); 
    push ( @jobs, \%record ); # test the global prefilled 
    push ( @jobs, \%job3 );   # test the global locally filled 
    $self->render(text => "Created job id $id. Jobs count: " . 
$#jobs ); 
}; 

get '/job/status' => sub { 
    my $self = shift; 
    my $out = "["; 
    for(my $i=0; $i<$#jobs+1; $i++) { 
        $out .= "{id:\""  . $jobs[$i]{id}      . "\","; 
        $out .= "," if $i<$#jobs; 
    } 
    $out .= "]"; 
    $self->render(text => "allJobsInfo($out). Num jobs: " . $#jobs); 
};

app->start();
Tameratamerlane answered 23/2, 2012 at 9:52 Comment(0)
B
7

This won't really work, as hypnotoad is using fork, not threads. I suggest storing data in something like a database or Cache::FastMmap.

Bellebelleek answered 23/2, 2012 at 10:32 Comment(2)
Thanks for the help. In the end, I moved to a solution with CouchDB. Looks pretty nice btw. :)Tameratamerlane
Alternative perl your.app daemon -l 'http://*:3000' could work, too. see Built-in web serverWingard

© 2022 - 2024 — McMap. All rights reserved.