develooper Front page | perl.ithreads | Postings from April 2010

Help with concurrent threads

Thread Next
From:
alfonso caponi
Date:
April 16, 2010 08:48
Subject:
Help with concurrent threads
Message ID:
o2y1ab6b3a11004160848kb941be1ax465ea577123d0a48@mail.gmail.com
#!/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"; 
			}
		}
	}
}

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About