lolibility
lolibility

Reputation: 2187

perl how to use is_running

my program is like:

use strict;
use threads;
use threads::shared;

my @thr;
for (my $i = 0; $i < $ARGV[0]; $i++) {
    $thr[$i] = threads->create(\&Iteration, $i);
}

foreach (@thr) {
    if ($_->is_running()) {
        print "no";
    }
    else{
        $_->join;
    }
}

sub Iteration {
    my $in = shift;
    print "test$in\n";
}

But when I run it with $ARGV[0], say 5, the output is

test2
test1
test0
test3
test4
Can't locate auto/threads/is_running.al in @INC 

So, how can I use the is_running() statement to check the status of one of my threads?

Upvotes: 1

Views: 797

Answers (2)

pilcrow
pilcrow

Reputation: 58534

If you really can't upgrade, you can implement is_running-like bookkeeping yourself with a shared table of thread IDs. Something like:

package Untested::Workaround;
#
# my $thr = Untested::Workaround->spawn(\&routine, @args);
# ...
# if (Untested::Workaround->is_running($thr)) ...
#
#
...
our %Running : shared;        # Keys are "running" tids

sub _bookkeeping {
  my ($start_routine, @user_args) = @_;
  my $ret;

  { lock(%Running); $Running{ threads->tid() } = 1; }
  $ret = $code->(@args);
  { lock(%Running); delete $Running{ threads->tid() }; }

  $ret;
}

sub spawn {
  shift; #ignore class
  threads->create(\&_bookkeeping, @_);
}

sub is_running { lock %Running; $Running{ $_[1]->tid() }; }

Again the above is untested. It could be improved, either subclassing threads or modifying threads' namespace to provide a more contemporary, more natural API. (It also disregards the caller context, something which threads preserves for its start routines.)

Upvotes: 1

ikegami
ikegami

Reputation: 385764

Looks right. That message indicates the sub doesn't exist, so I suspect you are using an older version of threads, one that did not have such a method. If so, just upgrade your threads module.

cpan threads

The following should give you the version you have installed (current is 1.86, is_running appears to have been added to 1.34):

perl -Mthreads -le'print $threads::VERSION'

The following should give you the documentation for the version you have installed:

perldoc threads

Upvotes: 1

Related Questions