我有以下perl互斥代码:
# ClaimMutex
#
# Return the mutex on success and undef on failure
#
# The mutex will be released if it's out of its scope
#
sub ClaimMutex {
my ($mutexName) = @_;
my $mutex = Win32::Mutex->new(0, $mutexName);
if (!defined $mutex) {
EPrint("Failed to create a mutex: $^E\n");
return;
}
if($mutex->wait(0) == 0) {
TPrint("Waiting for another instance of $mutexName to finish\n");
if ($mutex->wait() == 0) {
EPrint("Failed to get a $mutexName mutex lock: $^E\n");
return;
}
}
return OnDestroy($mutex, sub { $_[0]->Release(); });
}
我称之为:
sub Export
{
my ($rOptions) = @_;
my $mutex = ClaimMutex("export");
if (!defined $mutex)
{
return 1;
}
...
read from d:\foo.txt
copy d:\foo.txt to d:\foobackup.txt
write to d:\foo.txt
...
}
这是在两个独立的Perl实例上并行运行的。但是,我在运行时做了procmon,我看到一个实例打开了d:\ foo.txt进行写入,并且在另一个实例尝试打开它进行读取之前从未完成写入(并且打开失败)。我很困惑,因为我认为互斥锁会阻止这种情况。我验证了在foo.txt中做任何事情的唯一地方是在Export子目录中。你对可能发生的事情有任何建议吗?
答案 0 :(得分:0)
好的我明白了。
显然在互斥锁周围添加了一个条件(结果为真),但我认为在if方法之后,互斥锁超出了范围。
基本上,它看起来像:
if($trueVar == "1")
{
my $mutex = ClaimMutex("export");
if (!defined $mutex)
{
return 1;
}
}
答案 1 :(得分:-1)
您发布的内容不会受到您描述的错误的影响,以下情况也不会出现:
use strict;
use warnings;
use Object::Destroyer qw( );
use Win32::Mutex qw( );
sub mutex_nb {
my ($name) = @_;
my $mutex = Win32::Mutex->new(0, $name)
or die("Can't create mutex: $^E\n");
my $rv = $mutex->wait(0);
die("Can't wait for mutex: $^E\n")
if !defined($rv);
die("Can't wait for mutex: Abandonned mutex\n")
if $rv < 0;
return undef
if $rv == 0;
return Object::Destroyer->new($mutex, 'Release');
}
sub main {
my $mutex = mutex_nb('export')
or do {
print("Program already running.\n");
return;
};
print("Working...\n");
sleep(10);
print("done.\n");
}
main();
输出:
将来,请在您的问题中说明您的问题。