rakzer has asked for the wisdom of the Perl Monks concerning the following question:
The following code should always run a maximum of 20 threads processing some data. Running the code while looking at the memory consumption with top shows that the perl process keeps using more and more memory.
I am using perl 5.12.2 with threads 1.75 under FreeBSD 8.1 (64bit).
I am not sure where the memory leaks. Am I missing something?
#!/usr/bin/perl $|=1; use strict; use warnings; use threads; use threads::shared; use Data::Dumper; # Global vars # Maximum working threads my $MAX_THREADS = 20; # Flag to inform all threads that application is terminating my $TERM:shared=0; # Prevents double detach attempts my $DETACHING:shared; # Signal handling $SIG{'INT'} = $SIG{'TERM'} = sub { print("^C captured\n"); $TERM=1; }; # thread sub stuff_thr($) { my ($job)=@_; # My thread ID my $tid=threads->tid(); # do some thread stuff print "Hi, I am thread: $tid, I need to do something with $job\n"; # Detach and terminate { lock($DETACHING); threads->detach() if ! threads->is_detached(); } return(0); } # main sub main() { # Manage the thread pool until we run out of data or signalled # to terminate my @jobs=(1..100); while (@jobs && ! $TERM) { # Keep max threads running for (my $needed = $MAX_THREADS - threads->list(); $needed && ! $TERM; $needed--) { my $job = shift(@jobs); last if (! $job); # New thread threads->create('stuff_thr',$job); } # normally fetch a limited amount of data from a db to # process, at this point just make sure the job queue # is never empty if(scalar(@jobs) < 10) { @jobs=(1..100); } } while ((threads->list() > 0)) { # waiting for threads to finish sleep(1); } } # enter main() main();
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: threads: work crew memory leak
by BrowserUk (Patriarch) on Oct 16, 2010 at 15:52 UTC | |
by rakzer (Novice) on Oct 16, 2010 at 19:23 UTC | |
by BrowserUk (Patriarch) on Oct 16, 2010 at 20:03 UTC | |
by zwon (Abbot) on Oct 17, 2010 at 02:46 UTC | |
by BrowserUk (Patriarch) on Oct 17, 2010 at 03:05 UTC | |
by rakzer (Novice) on Oct 16, 2010 at 23:19 UTC | |
by perl-diddler (Chaplain) on Oct 17, 2010 at 05:48 UTC | |
by BrowserUk (Patriarch) on Oct 17, 2010 at 07:12 UTC | |
by rakzer (Novice) on Oct 17, 2010 at 09:59 UTC | |
by BrowserUk (Patriarch) on Oct 17, 2010 at 17:13 UTC | |
| |
Re: threads: work crew memory leak
by zwon (Abbot) on Oct 16, 2010 at 15:11 UTC |
Back to
Seekers of Perl Wisdom