我是perl中的線程的新手。使用信號量,而在perl中調用文件
我有一個項目列表(每個項目是在一個單獨的行)的文件,我想要並行構建這些項目。 目前,每個線程:
- 打開文件爲「已讀」模式
- 節省一些項目的列表(=一些文件行)
- 關閉
- 再次 - 打開文件作爲文件「寫」模式
- 重寫它沒有以確保每個線程訪問的F唯一一個選擇
,該線ile,即時嘗試使用信號量。
出於某種原因,線程collisons發生,我無法弄清楚我做錯了什麼。
我可以看到(在我的「報告」中也得到了每個版本的當前時間) 不同的線程從「共享」文件中選擇相同的項目(它只會在一段時間內發生,但仍然.. )
我甚至不確定如果我的$信號量decleration是合法的「我的」變量。
任何幫助將得到真正的讚賞!
謝謝。
這裏是我的代碼的一部分:
my $semaphore = Thread::semaphore->new() ;
sub build_from_targets_list{
#...
open(REPORT, "+>$REPORT_tmp"); # Open for output
#....
@threads =();
for ($i = 0; $i < $number_of_cores; $i++){
my $thr = threads->new(\&compile_process, $i,*REPORT);
push @threads, $thr;
}
$_->join for @threads;
close (REPORT);
}
### Some stuff..
sub compile_process{
*REPORT = shift(@_);
#...
while (1){
$semaphore->down();
open (DATA_FILE, $shared_file);
flock(DATA_FILE, 2);
while ($record = <DATA_FILE>) {
chomp($record);
push(@temp_target_list,$record);
}
# ... choose some lines (=projects)...
# remove the projects that should be built by this thread:
for ($k = 0; $k < $num_of_targets_in_project; $k++){
shift(@temp_target_list);
}
close(DATA_FILE);
open (REWRITE,">$shared_file");
flock(REWRITE, 2);
seek(REWRITE, 0, 0);
foreach $temp_target (@temp_target_list){
print REWRITE "$temp_target\n";
}
close (REWRITE);
## ... BUILD selected projects...
$semaphore->up();
}
}
謝謝!我會試試這個。 – user1625723