Paul
Paul

Reputation: 1014

perl: multithread write and tail file

I'm working on a simple use-case of perl multi-thread: one thread writes to a file and another thread tails the file. here is the code:

use strict;
use warnings;
use threads;
use File::Tail;

my $file = 'data.txt';
sub tail_file{
    my $file=File::Tail->new($file);
    while (defined(my $line=$file->read)) {
        print "$line";
    }
}

sub write_file{
    open (MYFILE, ">> $file");
    print MYFILE scalar localtime .  "  A data.\n";
    close (MYFILE); 
    print 'write done!';
}

my $t_tail = threads->new(\&tail_file);
$t_tail->join();

my $t_write = threads->new(\&write_file);
$t_write->join();



When running, this program is stuck on the console.

Upvotes: 3

Views: 1268

Answers (1)

Mansoor Siddiqui
Mansoor Siddiqui

Reputation: 21663

If you get rid of the call to $t_tail->join(), your program actually works fine. You need to get rid of this call because your $t_tail thread will run forever (and thus will never join), and your $t_write thread will never get kicked off.

You should know, however, that even if you get rid of that line, if the $t_write thread executes before the $t_tail thread (since the order of execution with threads is never guaranteed), then it may be the case you finish writing to the file before your File::Tail object is even initialized. And since File::Tail only captures changes to the file that happen after it is initialized, it may look like nothing is happening at all.

Lastly, you may think that File::Tail works similarly to the Linux/Unix tail, but the documentation shows that the default wait times used by the module are quite generous in comparison to the Linux/Unix counterpart:

maxinterval

The maximum number of seconds (real number) that will be spent sleeping. Default is 60, meaning File::Tail will never spend more than sixty seconds without checking the file.

interval

The initial number of seconds (real number) that will be spent sleeping, before the file is first checked. Default is ten seconds, meaning File::Tail will sleep for 10 seconds and then determine, how many new lines have appeared in the file.

If you run your program, and your File::Tail object does happen to get initialized before you start writing to the file, then you may have to wait a while (10 seconds) before you see anything on your console.

Upvotes: 3

Related Questions