Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: threads vs JSON

Below listed program fails with the following error:

JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this) at json_test.pl line 10.

Works fine when I comment out thread startup/join, or when JSON is parsed before thread is run. Message seems to be coming from JSON library, so I suppose something is wrong with it. Any ideas what's going on and how to fix it?

# json_test.pl
use strict;
use warnings;
use threads;
use JSON;
use Data::Dumper;

my $t = threads->new(\&DoSomething);
my $str = '{"category":"dummy"}';
my $json = JSON->new();
my $data = $json->decode($str);
print Dumper($data);
$t->join();

sub DoSomething
{
    sleep 10;
    return 1;
}
like image 451
AndyH Avatar asked May 14 '26 02:05

AndyH


1 Answers

JSON uses JSON::XS if installed which is not compatible with Perl threads (please don't take the author's words at face value - threads are discouraged and difficult to use effectively, but not deprecated and there are no plans to remove them). The community-preferred fork Cpanel::JSON::XS is thread safe and will be used by JSON::MaybeXS by default, which is a mostly drop-in replacement for JSON.

like image 57
Grinnz Avatar answered May 19 '26 05:05

Grinnz