Bitmap
Bitmap

Reputation: 12538

Concurrent sub-routines in Perl

I am attempting to get these two sub-routines running concurrently. When I fire the program I end up with:

Perl exited with active threads:
    2 running and unjoined
    0 finished and unjoined
    0 running and detached

Nothing gets print onto console. I was expected while(1) to stay active until SIGTERM.

Thread

use threads;

my $t1 = threads->create( \&sub2 );
my $t2 = threads->create( \&sub1 );

sub sub2 {
   my $dbh = get_connector();
   while (1) {
      print "Worker 2 Running";
      sleep 2;
   }
}

sub sub1 {
   while (1) {
      print "Worker 1 Running";
      sleep 1;
   }
}

Can you spot the defect here!

Upvotes: 1

Views: 181

Answers (2)

ikegami
ikegami

Reputation: 386706

You never wait for the children to end before exiting the process. Add

$_->join for threads->list;

Upvotes: 4

mpapec
mpapec

Reputation: 50677

Set

$| = 1;

to have unbuffered output, and make sure that your main thread does something while other thread are executing, ie.

sleep 1 while 1;

or wait for threads as @ikegami suggested

$_->join for $t1, $t2;

Upvotes: 2

Related Questions