简体   繁体   中英

Perl running two while loop subroutines in parallel

I am looking to run two subroutines in parallel, where both perform the same task on an android handset using ADB commands. With help from SO and other research I have produced the following code below, however I am new to multithreading and I get an error of 'Free to wrong pool' during execution. I am assuming I get this as I am using the $_ variable in both threads, is this correct? I am using Windows7 to run this, but my Perl interpreter crashes on running this script. Any guidance would be greatly appreciated. Thanks.

use strict;
use Win32::OLE;
use EFS_Handle;
use HelperFunctions;
use threads;

#### Various ADB command sequences follow ####
#### Start of multithread to run the same function on different android handsets ####

my @jobs;

push @jobs, threads->create(
    sub {
        print "\n\t" . curTime() . " :\t DUT Time at start of MPLMN search";

        open my $fh1, '>', "output.txt" or die "Cannot open output.txt: $!";
        my $pid1 = open my $log1, "-|", "adb -s 42d8d7dd logcat";

        system('adb -s 42d8d7dd shell input keyevent KEYCODE_ENTER');

        while (<$log1>) {
            $fh1->print($_);
            last if m/Sorted scan results/;
        }
        kill "TERM", $pid1;
        close $log1;
        print "\n\t" . curTime() . " :\t DUT Time at End of MPLMN search\n";
    }
);

push @jobs, threads->create(
    sub {
        print "\n\t" . curTime() . " :\t REF Time at start of MPLMN search";

        open my $fh, '>', "output.txt" or die "Cannot open output.txt: $!";
        my $pid = open my $log, "-|", "adb -s 0123456789ABCDEF logcat";

        system('adb -s 0123456789ABCDEF shell input keyevent KEYCODE_ENTER');

        while (<$log>) {
            $fh->print($_);
            last if m/EVENT_NETWORK_SCAN_COMPLETED/;
        }
        kill "TERM", $pid;
        close $log;
        print "\n\t" . curTime() . " :\t REF Time at End of MPLMN search\n";

    }
);

$_->join for @jobs;

The Win32::OLE module is famously not thread-safe

If you remove use Win32::OLE (you don't seem to use it) then your code will run fine

If have my doubts about adb cooperating with multiple simultaneous commands, but that is a different matter

I think the problem could be related to the fact you are writing from both threads to the same file "output.txt" with ">". Try opening them with ">>".

Also remember to close that file.

"I am assuming I get this as I am using the $_ variable in both threads..."

If you use strict, and $_ is in separate methods/subroutines, then there should be no global-access problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM