我是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