请帮助我。
我想根据用户请求创建线程。
示例:如果用户给出值7.那么我想创建7个线程
请在perl中回答
非常感谢:)
答案 0 :(得分:1)
创建线程的过程非常简单。
这将按照你的要求行事。它启动指定数量的线程,然后在所有线程上调用join
,等待它们完成。
毫无疑问,process
子程序需要更精细一些!
use strict;
use warnings;
use threads;
print 'Enter number of threads: ';
chomp(my $n = <STDIN>);
my @threads;
for (1 .. $n){
push @threads, threads->create(\&process, $_);
}
$_->join for @threads;
sub process {
my ($n) = @_;
sleep 1 + rand 5;
print "Ending thread $n\n";
}
答案 1 :(得分:0)
#!/usr/bin/Perl
use strict;
use threads;
my $num_of_threads = <STDIN>;
my @threads = init(); #initialize threads
# Loop through all threads
foreach(@threads){
# doWork is subroutine you want each thread to perform
$_ = threads->create(\&doWork);
}
# Join all threads
foreach(@threads){
$_->join();
}
sub init{
my @Threads;
for(my $i = 1;$i<=$num_of_threads;$i++){
push(@Threads,$i);
}
return @Threads;
}