1

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!

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Bitmap
  • 12,402
  • 16
  • 64
  • 91
  • 1
    Doesn't solve the issue but I can spot one defect...your code doesn't compile. You're missing a semicolon after the `print` in `sub1` – ThisSuitIsBlackNot Oct 16 '13 at 17:54
  • 1
    Possible duplicate of [this question](http://stackoverflow.com/questions/2949967/perl-running-simultaneous-routines). use strict; use warnings; – mikew Oct 16 '13 at 17:58
  • @ThisSuitIsBlackNot It was typo while constructing this post. Nice spot though! ;-) – Bitmap Oct 16 '13 at 18:03

2 Answers2

4

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

$_->join for threads->list;
ikegami
  • 367,544
  • 15
  • 269
  • 518
2

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;
mpapec
  • 50,217
  • 8
  • 67
  • 127