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

Recent Comments