2009-09-26 77 views

回答

7

最新版本的Perl具有线程支持。运行perl -V:usethreads以查看它是否在您的系统中可用。

$ perl -V:usethreads 
usethreads='define' 

perldoc threads给出了一个很好的使用它们的介绍。

+2

切勿使用的ithread什么。 – jrockway 2009-09-26 09:50:53

+0

链接不工作 – 2014-08-04 14:45:22

7

如果性能是不是一个大问题,然后fork荷兰国际集团多个进程可能比处理线程容易得多。我经常使用Parallel::ForkManager这非常简单,但非常擅长它。

5

这听起来像你不需要先发制人的多线程;在这种情况下,请看POE的合作模式。由于您的代码在您决定时只会屈服于其他线程,并且一次只能运行一个线程,所以开发和调试将更容易。

+3

值得注意的是,虽然POE不会隐支持多线程或多处理,'POE ::轮:: Run'让您在派生进程中运行的一段代码,翻译它的I/O和退出状态进入POE活动。有时,封装代码是非常有用的。 – hobbs 2009-09-26 07:59:03

+0

我那秒_ – xxxxxxx 2009-09-28 12:34:03

2

Coro是合作多任务一个很好的模块。

99%的时间,这是你需要的,如果你想在Perl中的线程。

如果你想线程以加快你的代码时,多个核心可用,你会走上错误的道路。 Perl比其他语言慢了50倍。将代码重写为在两个CPU上运行意味着它现在在一个CPU上的运行速度比其他语言慢25倍。最好花费精力将缓慢的部分移植到不同的语言。

但如果你只是不想IO阻止其他“线程”,然后科罗正是你想要的。

+1

还有发展速度。 – 2009-09-26 21:46:21

+0

我厌倦了这种说法:)我可以像在Perl中一样在Haskell中快速破解许多事情,而Haskell的运行速度比Perl快得多。 – jrockway 2009-09-27 00:55:14

+0

我同意这一点,但声称Perl比其他语言慢了50倍是一种夸大,只适用于某些操作。如您所知,Perl的IO和正则表达式与最好的编译语言一致。如果一个程序员可以识别瓶颈并让开发人员有时间,那么使用Inline :: C可能需要在DSL中编写一些代码。如果他们必须重写DSL中的大部分代码以获得良好的性能加速,那么完全放弃Perl可能是有意义的。 – 2012-10-02 14:24:22

9

有很多原因可能导致您不想多线程。但是,如果您确实想要多线程,下面的代码可能是一个有用的示例。它创建了一些作业,将它们放入一个线程安全的队列中,然后启动一些从队列中取出作业并完成作业的线程。每个线程在循环中不断从队列中提取作业,直到看不到任何作业。程序等待所有线程完成,然后打印它在工作中花费的总时间。

#!/usr/bin/perl 

use threads; 
use Thread::Queue; 
use Modern::Perl; 

my $queue= Thread::Queue->new; 
my $thread_count= 4; 
my $job_count= 10; 
my $start_time= time; 
my $max_job_time= 10; 

# Come up with some jobs and put them in a thread-safe queue. Each job 
# is a string with an id and a number of seconds to sleep. Jobs consist 
# of sleeping for the specified number of seconds. 
my @jobs= map {"$_," . (int(rand $max_job_time) + 1)} (1 .. $job_count); 
$queue->enqueue(@jobs); 

# List the jobs 
say "Jobs IDs: ", join(", ", map {(split /,/, $_)[0]} @jobs); 

# Start the threads 
my @threads= map {threads->create(sub {function($_)})} (1 .. $thread_count); 

# Wait for all the threads to complete their work 
$_->join for (@threads); 

# We're all done 
say "All done! Total time: ", time - $start_time; 

# Here's what each thread does. Each thread starts, then fetches jobs 
# from the job queue until there are no more jobs in the queue. Then, 
# the thread exists. 
sub function { 
    my $thread_id= shift; 
    my ($job, $job_id, $seconds); 
    while($job= $queue->dequeue_nb) { 
    ($job_id, $seconds)= split /,/, $job; 
    say "Thread $thread_id starting on job $job_id ", 
     "(job will take $seconds seconds)."; 
    sleep $seconds; 
    say "Thread $thread_id done with job $job_id."; 
    } 
    say "No more jobs for thread $thread_id; thread exiting."; 
} 
相关问题