Sometimes it’s important that the same event doesn’t occur at the same moment. For example a an order conformation is reposted. Normally you would see that the status is already set to processed and skip it. But what it the second HTTP request is quickly after the first (because the user pressed refresh or a proxy had a hick up or …) and the order has not yet been fully processed. To fix this you need a semaphore.

You can use the system V semaphore functions, but another option is to use APC.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * A very simple semaphore for mutual exclusion.
 * It will hold it for max 60 sec. Remember to release when done.
 *
 * @param string $key
 */
function getSemaphore($key)
{
    while (!apc_add("semaphore:{$key}", getmypid(), 60)) sleep(0.5);
}
 
/**
 * Release the semaphore, grabbed with getSemaphore($key).
 *
 * @param string $key
 */
function releaseSemaphore($key)
{
    apc_delete("semaphore:{$key}");
}
/**
 * A very simple semaphore for mutual exclusion.
 * It will hold it for max 60 sec. Remember to release when done.
 *
 * @param string $key
 */
function getSemaphore($key)
{
	while (!apc_add("semaphore:{$key}", getmypid(), 60)) sleep(0.5);
}

/**
 * Release the semaphore, grabbed with getSemaphore($key).
 *
 * @param string $key
 */
function releaseSemaphore($key)
{
	apc_delete("semaphore:{$key}");
}

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

   

Questions? Just ask!

About the author

Hi, I'm Arnold Daniels. How nice that you like to know a bit more about little old me :).

I've spend a big part of my life behind a computer (and not playing games). I've learned a lot about databases, programming and system administration especially on. the LAMP stack (Linux, Apache, MySQL & PHP).

Have a look at what I'm working on now!
© 2012 Jasny · web development Suffusion theme by Sayontan Sinha