perl share filehandle with threads

隐身守侯 提交于 2019-12-04 21:31:24

Can I share a filehandle between threads

No.

that every thread deal with one line of a file and loop ends when the file reaches the last line?

Yes. Just feed the lines from the file instead of numbers to the worker threads.

By the way, you don't need 11 queues to do that. You just need one:

#!/usr/bin/perl

use strict;
use warnings;

use threads 1.39;
use threads::shared;
use Thread::Queue qw( );

# Maximum working threads
my $NUM_WORKERS = 10;

# Flag to inform all threads that application is terminating
my $TERM :shared = 0;

my $request_q = Thread::Queue->new();

$SIG{INT} = $SIG{TERM} = \&signal_handler;

exit(main());

sub signal_handler {
    print(">>> Terminating <<<\n");
    $TERM = 1;
}    

sub main {
    my @threads;
    push @threads, threads->create(\&worker)
        for 1..$NUM_WORKERS;

    while (!$TERM && defined(my $job = <>)) {
        chomp($job);
        $request_q->enqueue($job);
    }

    # Signal to threads that there is no more work.
    $q->enqueue(undef) for 1..$NUM_WORKERS;

    # Wait for all the threads to finish.
    $_->join() for @threads;

    print("Done\n");
    return 0;
}

sub worker {
    my $tid = threads->tid();

    while (!$TERM && defined(my $job = $request_q->dequeue())) {
        printf("            %2d <- Working\n", $tid);

        # Do something with $job.
        sleep(1+rand(3));
    }

    printf("Finished -> %2d\n", $tid);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!