Trying to override IO :: Tee :: PRINT for thread safety

Thanks to some help , I started trying to get thread safe logging working for my script - however, it seems I don't have it working correctly:

use Fcntl ':flock';

no warnings 'redefine';
sub IO::Tee::PRINT
{
    my $self = shift;
    my $ret = 1;
    foreach my $fh (@$self) {
        flock($fh, LOCK_EX);
        print "\n\t\ttestA\n";  #<-- added for testing
        undef $ret unless print $fh @_;
        flock($fh, LOCK_UN);
        print "\t\ttestB\n";    #<-- added for testing
    }
    return $ret;
}

my $Info_tee = IO::Tee->new(\*STDOUT, ">$ENV{DOM}\\build.log");

When I get to the threaded section of my script:

print $Info_tee "\n------------------------------------------------------\n";
print $Info_tee "\n\t\t*** Performing Action: \'$cmd\' on $comp ***";

My output in STDOUT(4 threads):

                testA
                testA

------------------------------------------------------
                testB

                testA

------------------------------------------------------
                testB

------------------------------------------------------
                testB

                testA

                testA

------------------------------------------------------
                testB

.. and then the script closes. What am I doing wrong?

Edit: I created a simple example of my problem here - I noticed that if you remove the queue from the script, everything seems to work as designed.

+4
source share
3 answers

Easy way

. , :

use threads;
use threads::shared;

my $mutex : shared; # will synchronize access to our shared IO::Tee resource

async {
  ...
  { lock $mutex; print $shared_resource "I did something"; }
  ...
}

: - . flock friends , .

, , , , : IO:: Tee , , .

? IO:: Tee . ( , PRINT/PRINTF .) tie() d , GLOB ARRAY, . perl, arrayrefs . , , , .

+1

, .


, script , , .


, , - , , , .

STDOUT->flush();
$fh->flush();

, , , ( ).

------------------------------------------------------
------------------------------------------------------
*** Performing Action: 'action' on comp1 ***
*** Performing Action: 'action' on comp2 ***
0

Source: https://habr.com/ru/post/1537928/


All Articles