title: Can I reuse joined threads in perl?
body: <p>I have a module that is running multiple threads and pushing them onto a list of threads.</p>
  
  <p>ex:</p>
  
  <pre><code>#!/usr/bin/perl
  
  #test_module.pm
  
  package test_module;
  
  use strict;
  use warnings;
  use threads;
  
  sub main {
  
      my $max_threads = 10;
      my @threads     = ();
  
      # create threads
      while (scalar @threads &lt; $max_threads) {
          my $thread = threads-&gt;new(\&amp;thread_sub);
          push @threads, $thread;
      }
  
      # join threads
      for my $thread (@threads) {
          $thread-&gt;join();
      }
  }
  
  sub thread_sub {
      my $id = threads-&gt;tid();
      print "I am in thread $id\n";
  }
  
  1;
  </code></pre>
  
  <p>The problem is that I am calling this module multiple times from one Perl script and instead of eliminating the old threads and creating new ones, the thread ids just keep incrementing.  I have heard that if you don't properly get rid of old threads in Perl this will cause a memory leak and slow your program down, is this true?  Is the data from my old threads just sitting in memory taking up space?</p>
  
  <p>If so this can become a large problem since my script will be part of a much larger program that may generate hundreds or thousands of threads all of which would just be taking up memory even after they are done being used.  How can I stop this from happening? Can my threads be reused?</p>
  
  <p>Here is an example script that will call the module and show how the threads will continue to increment even though I joined the old threads (I thought that "join" was how you cleaned up after them, am I doing something wrong?)  The way this script will be used I can't afford to have memory from old threads sitting there taking up space.</p>
  
  <p>ex:</p>
  
  <pre><code>#!/usr/bin/perl
  
  #testing.pl
  
  use strict;
  use warnings;
  use test_module;
  
  test_module::main();
  test_module::main();
  test_module::main();
  
  system 'pause';
  </code></pre>
  
  <p>Thanks!</p>