Perl seg error when connecting threads

I have code similar to the one below. I have one main script that calls another module called initial.pm. initial.pm opens a connection to the AMQP server (in my case, RabbitMQ) and using the Net :: AMQP :: RabbitMQ library to establish a connection. Everything works fine, except when I try to join my threads, I get a segmentation fault .

I think Net :: AMQP :: RabbitMQ is not thread safe. But this is only used by the main thread. I am sure that you can reproduce the error by simply copying and skipping the codes below.

How to fix it?

main.pl

#!/usr/bin/perl
use Cwd qw/realpath/;
use File::Basename qw/dirname/;
use lib 'lib';
use threads;
use threads::shared;
use initial;

my @threads = ();
my $run :shared = 1;

my $init = load initial($name);

$SIG{'TERM'} = sub {
    $run = 0;
};

threads->create(\&proc1);
threads->create(\&proc2);


while($run){
    sleep(1);
    print "I am main thread\n";
}

$_->join() for threads->list();

sub proc1 {
    while($run){
        sleep(1);
        print "I am child thread 1 \n"
    }
}

sub proc2 {
    while($run){
       sleep(1);
       print "I am child thread 2 \n";
    }
}

Library /initial.pm

package initial;

use Net::AMQP::RabbitMQ;
use Cwd qw/realpath/;
use File::Basename qw/dirname/;

my $mq;
my $stop = 0;

sub load {
    my $class = shift;
    my $self = {};
    connectq();
    bless $self,$class;
    return $self;
}

sub connectq {
    $mq = Net::AMQP::RabbitMQ->new();
    my ($host,$port,$user,$pass) = ('localhost','5672','guest','guest');
    $mq->connect($host, {
        user => $user,
        password => $pass,
        port => $port,
        timeout => 10,
    });

    $mq->channel_open(1);
    $mq->consume(1, 'logger');
}

1;
+2
source share
1

, .

"" - - "" , .

, , .

(- ):

#!/usr/bin/env perl

use strict;
use warnings;

use XML::Twig;
use Data::Dumper;

sub thread1 {
    print threads->self->tid.": Includes:", Dumper \%INC,"\n";
}


#main;

print "Main includes:", Dumper \%INC,"\n";
threads -> create ( \&thread1 );

, XML::Twig . "" ( ), .

, :

#!/usr/bin/env perl

use strict;
use warnings;

use threads;
use Data::Dumper;

sub thread1 {
    require XML::Twig;
    XML::Twig -> import;
    print threads->self->tid.": Includes:", Dumper (\%INC),"\n";
}


#main;

print "Main includes:", Dumper (\%INC),"\n";
threads -> create ( \&thread1 );
foreach my $thr ( threads -> list ) { 
   $thr -> join;
}

- , .

- fork ing thread ing... . " ".

. , . , . var - , - . share $init, , / .

" " , , Thread::Queue / .

+1

All Articles