我正在处理 perl 多线程的一个简单用例:一个线程写入文件,另一个线程跟踪文件。这是代码:
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();
运行时,这个程序卡在控制台。
最佳答案
如果你去掉对 $t_tail->join()
的调用,你的程序实际上可以正常工作。您需要摆脱此调用,因为您的 $t_tail
线程将永远运行(因此永远不会 join
),而您的 $t_write
线程永远不会被踢掉。
然而,您应该知道,即使您去掉了那一行,如果 $t_write
线程在 $t_tail
线程之前执行(因为执行顺序永远不会保证使用线程),那么可能是您在 File::Tail
对象初始化之前就完成了对文件的写入。由于 File::Tail
仅捕获文件初始化之后发生的更改,因此它可能看起来什么都没有发生。
最后,您可能认为 File::Tail
的工作方式类似于 Linux/Unix tail
,但是 documentation表明与 Linux/Unix 对应模块相比,模块使用的默认等待时间相当慷慨:
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.
如果您运行您的程序,并且您的 File::Tail
对象恰好在您开始写入文件之前得到初始化,那么您可能需要等待一段时间(10 秒)才能写入在您的控制台上看到任何东西。
关于multithreading - perl:多线程写和尾文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8176925/