我試圖完成以下任務:Perl的隊列和線程
有一個線程,從一個非常大的文件中讀取數據說一下 10GB,並將其推入隊列。 (我不希望爲隊列 變得非常大任)
雖然
buildQueue
線程在同一時間將數據推送到隊列中有 約5個工作線程去排隊和處理數據。
我做了一個嘗試,但我的其他線程無法訪問,因爲我的buildQueue
線程連續循環。
我的方法可能完全錯誤。感謝您的幫助,非常感謝。
下面的代碼爲buildQueue
:
sub buildQueue {
print "Enter a file name: ";
my $dict_path = <STDIN>;
chomp($dict_path);
open DICT_FILE, $dict_path or die("Sorry, could not open file!");
while (1) {
if (<DICT_FILE>) {
if ($queue->pending() < 100) {
my $query = <DICT_FILE>;
chomp($query);
$queue->enqueue($query);
my $count = $queue->pending();
print "Queue Size: $count Query: $query\n";
}
}
}
}
正如我所預料,當此線程被什麼別的執行後會被執行,因爲該線程將無法完成。
my $builder = new Thread(&buildQueue);
由於構建器線程將運行很長時間,所以我永遠不會創建工作線程。
這裏是整個代碼:
#!/usr/bin/perl -w
use strict;
use Thread;
use Thread::Queue;
my $queue = new Thread::Queue();
my @threads;
sub buildQueue {
print "Enter a file name: ";
my $dict_path = <STDIN>;
chomp($dict_path);
open dict_file, $dict_path or die("Sorry, could not open file!");
while (1) {
if (<dict_file>) {
if ($queue->pending() < 100) {
my $query = <dict_file>;
chomp($query);
$queue->enqueue($query);
my $count = $queue->pending();
print "Queue Size: $count Query: $query\n";
}
}
}
}
sub processor {
my $query;
while (1) {
if ($query = $queue->dequeue) {
print "$query\n";
}
}
}
my $builder = new Thread(&buildQueue);
push @threads, new Thread(&processor) for 1..5;
幾個問題:你提到你的隊列,構造器線程將無法完成,但它做了什麼呢?隊列大小是否低於100或高於0?另外,[我不確定你是否正確創建你的線程](http://perldoc.perl.org/perlthrtut.html)。不應該是'我的$ builder = threads-> create(\&buildQueue);'? – 2012-02-13 11:57:11
隊列生成器生成正常,但由於工作線程並沒有達到要創建這樣的隊列是停留在100,而構建的隊列仍然是因爲連續循環的運行不能從隊列中刪除任何東西。 – Sinista 2012-02-13 12:19:14
嗯,我需要看到更多的代碼,以建立背景下,特別是在創建線程。在創建工作線程之前,您不是「連接」或「分離」隊列構建器,對吧? – 2012-02-13 12:20:02