检查IPC共享锁

发布于 2024-12-16 15:11:25 字数 556 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

开始看清了 2024-12-23 15:11:25

你想做一个非阻塞锁。锁定调用将立即返回。如果锁可用,则锁调用的返回值为 true,并且您将获得锁。如果返回值为 false,则表明其他资源拥有该资源。

if ($resource_handle -> shlock(LOCK_EX | LOCK_NB)) {
    print "Got lock in parent\n";
    $resource_handle -> shunlock();
} else {
    print "The shared resource is locked\n";
}

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.

if ($resource_handle -> shlock(LOCK_EX | LOCK_NB)) {
    print "Got lock in parent\n";
    $resource_handle -> shunlock();
} else {
    print "The shared resource is locked\n";
}
千里故人稀 2024-12-23 15:11:25

据我所知,你有竞争条件。您假设子级将在父级检查句柄之前锁定资源。根据您提供的代码,这表明 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文