1

I want to use threads in loops. The way I want to use this is that start threads in a loop and wait for them to finish. Once all threads are finished then sleep for some predefined number of time and then start those threads again.

Actually I want to run these threads once every hour and that is why I am using sleep. Also I know that hourly run can be done via cron but I can't do that so I am using sleep.

I am getting this error when I am trying to run my code:

Thread already joined at ex.pl line 33.
Perl exited with active threads:
5 running and unjoined
0 finished and unjoined
0 running and detached

This is my code:

use strict;
use warnings;
use threads;
use Thread::Queue;

my $queue = Thread::Queue->new();
my @threads_arr;

sub main {
    $queue->enqueue($_) for 1 .. 5;
    $queue->enqueue(undef) for 1 .. 5;

}

sub thread_body {
    while ( my $num = $queue->dequeue() ) {
        print "$num is popped by " . threads->tid . " \n";
        sleep(5);
    }
}

while (1) {
    my $main_thread = threads->new( \&main );
    push @threads_arr, threads->create( \&thread_body ) for 1 .. 5;

    $main_thread->join();

      foreach my $x (@threads_arr) {
          $x->join();
      }

    sleep(1);
    print "sleep \n";
}

Also I am able to see other questions similar to this but I am not able to get any of them.

1 Answer 1

4

Your @threads_arr array never gets cleared after you join the first 5 threads. The old (already joined) threads still exist in the array the second time around the loop, so Perl throws the "Thread already joined" error when attempting to join them. Clearing or locally initializing @threads_arr every time around the loop will fix the problem.

@threads_arr=(); # Reinitialize the array
push @threads_arr, threads->create( \&thread_body ) for 1 .. 5;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.