1 perl
我正在运行尝试在perl中同时运行两个子例程.这样做的最佳方法是什么?例如:
sub 1{
print "im running";
}
sub 2{
print "o hey im running too";
}
Run Code Online (Sandbox Code Playgroud)
如何一次执行这两个例程?
使用threads.
use strict;
use warnings;
use threads;
sub first {
my $counter = shift;
print "I'm running\n" while $counter--;
return;
}
sub second {
my $counter = shift;
print "And I'm running too!\n" while $counter--;
return;
}
my $firstThread = threads->create(\&first,15); # Prints "I'm running" 15 times
my $secondThread = threads->create(\&second,15); # Prints "And I'm running too!"
# ... 15 times also
$_->join() foreach ( $firstThread, $secondThread ); # Cleans up thread upon exit
Run Code Online (Sandbox Code Playgroud)
您应该注意的是打印是如何不规则地交错的.不要试图在执行顺序良好的错误前提下进行任何计算.
Perl线程可以使用以下方式进行相互通信:
use threads::shared;)use Thread::Queue;)use Thread::Semaphore;)有关更多信息和优秀教程,请参阅perlthrtut.