tags:

views:

30

answers:

1

hi all

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);
}

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 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"?

+1  A: 

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.

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.
 */

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

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.

caf
i seemaybe you have an idea how to synchronize processes in a particular order?if there is no other way ill have to use flock
John Doe
@John Doe: Yes, use SysV semaphores. See the update to my answer.
caf