2009-09-26 42 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."; 
} 
相關問題