羊群锁定顺序? [英] flock locking order?

查看:80
本文介绍了羊群锁定顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im使用来自以下内容的简单测试脚本 http://www.tuxradar.com/practicalphp/8/11/0 像这样

im using a simple test script from http://www.tuxradar.com/practicalphp/8/11/0 like this

<?php
$fp = fopen("foo.txt", "w");
if (flock($fp, LOCK_EX)) {
    print "Got lock!\n";
    sleep(10);
    flock($fp, LOCK_UN);
}

我打开了5个shell,一个接一个地执行了脚本 脚本会一直阻塞,直到释放锁为止,然后在释放后继续

i opened 5 shell's and executed the script one after the other the scripts block until the lock is free'ed and then continues after released

im并没有真正对php感兴趣,但是我的问题是: 有人知道flock()的获取顺序吗?

im not really interessted in php stuff, but my question is: anyone knows the order in which flock() is acquired?

e.g.
t0: process 1 lock's
t1: process 2 try_lock < blocking
t2: process 3 try_lock < blocking
t3: process 1 releases lock
t4: ?? which process get's the lock?

是否存在简单的确定性顺序,例如队列,还是内核只是"通过更高级的规则"来选择一个?

is there a simple deterministic order, like a queue or does the kernel 'just' pick one by "more advanced rules"?

推荐答案

如果有多个进程在等待排他锁,则未指定哪个进程首先成功获取了它.不要依赖任何特定的顺序.

If there are multiple processes waiting for an exclusive lock, it's not specified which one succeeds in acquiring it first. Don't rely on any particular ordering.

话虽如此,当前的内核代码以阻塞的顺序唤醒它们.此评论在fs/locks.c:

Having said that, the current kernel code wakes them in the order they blocked. This comment is in fs/locks.c:

/* Insert waiter into blocker's block list.
 * We use a circular list so that processes can be easily woken up in
 * the order they blocked. The documentation doesn't require this but
 * it seems like the reasonable thing to do.
 */


如果要按顺序运行一组进程,请不要使用flock().使用SysV信号量(semget()/semop()).


If you want to have a set of processes run in order, don't use flock(). Use SysV semaphores (semget() / semop()).

为第一个进程后的每个进程创建一个包含一个信号量的信号量集,并将它们全部初始化为-1.对于第一个之后的每个进程,在该进程的信号量上执行semop(),其sem_op值为零-这将阻止它.第一个进程完成后,应在第二个进程的信号量上执行semop(),其sem_op值为1-这将唤醒第二个进程.第二个进程完成后,应在第三个进程的信号量上执行semop(),其sem_op值为1,依此类推.

Create a semaphore set that contains one semaphore for each process after the first, and initialise them all to -1. For every process after the first, do a semop() on that process's semaphore with a sem_op value of zero - this will block it. After the first process is complete, it should do a semop() on the second process's semaphore with a sem_op value of 1 - this will wake the second process. After the second process is complete, it should do a semop() on the third process's semaphore with a sem_op value of 1, and so on.

这篇关于羊群锁定顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆