Search code examples
multithreadingperlsleepthread-sleep

Perl Threads: How does Sleep() behave


I have the following Perl Script that creates 10 threads and and calls a function 1000 times. In this function there is just a print (for debugging) and sleep(5)

Here is the Perl Script:

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

my $fetch_q   = Thread::Queue->new();
sub fetch {
    while ( my $num = $fetch_q->dequeue() ) { 
        print "$num\n";
        sleep(5);
    }
}

my @workers = map { threads->create( \&fetch ) } 1 .. 10;
$fetch_q->enqueue( 1 .. 1000 );
$fetch_q->end();
foreach my $thr (@workers) {$thr->join();}

When I call sleep(5) it seems like the entire program comes to a halt (is this correct?). Also how would I make an individual thread sleep?


Solution

  • When I call sleep(5) it seems like the entire program comes to a halt (is this correct?).

    Are you saying you only see one number every 5 seconds? I see 10 numbers every 5 seconds, meaning sleep only puts the current thread to sleep.

    You can see it more clearly using the following program:

    use threads;
    
    async {
       print "Before sleep\n";
       sleep 5;
       print "After sleep\n";
    };
    
    async {
       for (1..6) {
          print "Boop\n";
          sleep 1;
       }
    };
    
    $_->join for threads->list;
    

    Output:

    Before sleep
    Boop
    Boop
    Boop
    Boop
    Boop
    After sleep
    Boop
    

    Also how would I make an individual thread sleep?

    There are ways to achieve this without using sleep, but I think you're wrong about sleep not doing exactly this.