Hi list,

I've some doubts with a multi-threads script. My goal is to create a script
with the same max number of threads running at all times.

For example: I've an array with 9 elements and 3 threads to process it; each
thread can process an element using a different time (a thread could end
before another) and I would like 3 threads always running.

My idea is to take an element from a queue, start threads to reach the
maximum number of active threads allowed and simultaneously start a separate
(but unique) thread to wait every thread in execution.

In attachment my "solution". Have you any tips? I would not use other
modules as well threads, threads::shared, thread::queue.

Thank you very much!
Al
#!/usr/bin/perl -w

$|=1;

use strict;
use threads;
use threads::shared;
use Thread::Queue;

my $maxthreads = 3;

my @users = ('jim','jane','tom','tim','al','ed','mary','kim','meg');

our $q :shared;

$q = new Thread::Queue;

# fill the queue
$q->enqueue($_) for @users;

# thread to wait (join) the threads
my $MonitorRunningThreads = threads->new(\&MonitorRunningThreads);

my $n = $q->pending;
print "Elements in the queue : $n\n";

# while the queue is not empty
while ($q->pending > 0) {
        # if the running threads list is <= the max threads
        if ((threads->list(threads::running)) <= $maxthreads) {
                my $thr = threads->new(\&UseMe,$q->dequeue_nb);
        }
}

print "\n\nwaiting...\n";

# wait again the last threads; > 1 because MonitorRunningThreads thread is 
running 
while ((threads->list(threads::running)) > 1){};

exit(0);

sub UseMe {
        my $user = shift;
        my $sleep_time = rand(5);
        print "$user sleep for $sleep_time seconds...\n";
        sleep $sleep_time;
}

# wait the threads
sub MonitorRunningThreads {
        while(1) {
                foreach my $thr (threads->list(threads::joinable)) { 
                        if ($thr->tid && !threads::equal($thr, threads->self) 
&& !threads::equal($thr,$MonitorRunningThreads)){ 
                                print "\tWaiting for thread " . $thr->tid . " 
to join\n";
                                print "\tThread " . $thr->join . " has 
joined.\n"; 
                        }
                }
        }
}

Reply via email to