在多线程perl程序中使用公共日志文件

时间:2014-05-27 09:29:04

标签: multithreading perl

我已经尝试过以下代码在多线程程序中编写公共日志,并且如果达到3mb则必须剪切文件并创建新文件。到达3mb后创建新文件但是已经打开的文件是关闭不关闭,在该文件中所有线程都在写,在新的日志文件中只有一个线程能够写。任何人都可以帮我解决这个问题。我想每次都创建一个新的公共日志文件当它在多线程程序中达到3mb时。

use strict;
use warnings;
use threads;
use POSIX qw(strftime);


my $count;
my $thread_count=5;
my @threads;
my $date_string = strftime "%Y%m%d\_%H\_%M\_%S",localtime;
my $log_file_name="log\_$date_string.log";

open(LOG,"+>","log\_$date_string.log")or die "cant open the file";


for ($count = 1; $count <=$thread_count ; $count++) 
{
    my $thread = threads->new(\&process);
    push(@threads,$thread);        

}

foreach (@threads) 
{
   $_->join;
}
close LOG;

sub process
{  
   for(1..100000)
   {
       my $id=threads->tid(); 

        print LOG "$id I need a perl script using multi thread to write a common log file and when the file becomes of 3mb it should be closed and new common log file should be created \n.";

    if(stat("$log_file_name")->size >(3*1024*10240))
    {
         close LOG;
         $date_string = strftime "%Y%m%d\_%H\_%M\_%S",localtime;
         $log_file_name="log\_$date_string.log";
         open(LOG,"+>","log\_$date_string.log")or die "cant open the file";                  
    }

   }

}

1 个答案:

答案 0 :(得分:2)

我在许多并行进程中使用了Log :: Log4Perl,就像魅力一样,尝试这个http://search.cpan.org/perldoc?Log%3A%3ALog4perl