检查IPC共享锁
在 perl 中使用 IPC::Shareable 时如何检查锁是否被其他人持有。 我有以下代码:
my $resource = 0;
my $resource_handle = tie $resource, 'IPC::Shareable', undef , { destroy => 1 };
my $child = fork;
unless ($child) {
$resource_handle -> shlock();
sleep 10;
$resource_handle -> shunlock();
exit(0);
}
sleep 2;
if ($resource_handle -> shlock(LOCK_EX)) {
print "Got lock in parent\n";
$resource_handle -> shunlock();
} else {
print "The shared resource is locked\n";
}
10 秒后打印“在父级中获得锁定”,而我希望它打印“共享资源已锁定”。
How can I check if a lock is held by someone else while using IPC::Shareable in perl.
I have the below code:
my $resource = 0;
my $resource_handle = tie $resource, 'IPC::Shareable', undef , { destroy => 1 };
my $child = fork;
unless ($child) {
$resource_handle -> shlock();
sleep 10;
$resource_handle -> shunlock();
exit(0);
}
sleep 2;
if ($resource_handle -> shlock(LOCK_EX)) {
print "Got lock in parent\n";
$resource_handle -> shunlock();
} else {
print "The shared resource is locked\n";
}
This prints "Got lock in parent" after 10 seconds while I want it to print "The shared resource is locked".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你想做一个非阻塞锁。锁定调用将立即返回。如果锁可用,则锁调用的返回值为 true,并且您将获得锁。如果返回值为 false,则表明其他资源拥有该资源。
You want to do a non-blocking lock. The lock call will return right away. If the lock was available, the return value of the lock call will be true and you will have acquired the lock. If the return value is false, then something else possesses the resource.
据我所知,你有竞争条件。您假设子级将在父级检查句柄之前锁定资源。根据您提供的代码,这表明 fork 后的 exec 占用子进程的时间不会超过父进程在 0 上分支所需的时间。(这对我来说似乎很明智。)除非您强制父进程休眠,我没有看到您的代码和结果表明有任何问题。
From what I can see, you have a race condition. You assume that the child will lock the resource before the parent checks the handle. With the code you gave, this indicates no more than the exec after the fork is taking the child process longer than it takes the parent process to branch on 0. (And that seems sensible to me.) Unless you force a sleep in the parent, I don't see that your code and your results indicate any problem.