Semaphores - feature request
| From: | Wojciech Malota | Date: | Mon, 01 Jan 2007 08:45:08 +0000 |
| Subject: | Semaphores - feature request | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-246314@lists.php.net to get a copy of this message | ||
It's impossible to correct remove semaphores with sem_remove function
when I use them to provide execution of concurrent processes.
When the last process releases the semaphore I should be able to remove
it. But I don't know if another process haven't acquired the semaphore.
For safety reasons I don't remove released semaphores from system.
Now, If I get 128 semaphores and I execute sem_get one more time I will
get warning.
So, I can't remove semaphores (because I don't know if another process
is using it) and I can't get next semaphore.
I will try to tell about my sugestion.
I assume that I have a function my_sem_remove($sem_id):
function my_sem_remove($id) {
if(Semaphore $id isn't acquired and its FIFO is empty)
sem_remove($id);
}
None of instructions in this function can be interrupted.
So, now the problem is simple to resolve:
$id = sem_get(ID);
sem_acquire($id);
CRITICAL REGION
sem_release($id);
my_sem_remove($id);
But now, two instructions: sem_release and my_sem_remove are not needed.
It's simple to replace them by one function my_sem_release:
function my_sem_release($id) {
sem_release($id);
my_sem_remove($id);
}
For reasons which about I will write later those instructions can't be
interrupted.
So, my example look like this:
$id = sem_get(ID);
sem_acquire($id);
CRITICAL REGION
my_sem_release($id);
But let's imagine two concurrent processes executing code above:
PROC1: $id = sem_get(ID);
<--- interrupt
PROC2: $id = sem_get(ID);
sem_acquire($id);
CRITICAL REGION
my_sem_release($id);
<--- interrupt
PROC1: sem_acquire($id); <--- Uuups!! Error: semaphore doesn't exists,
PROC2 has removed it.
My solution:
Instructions sem_get and sem_acquire can't be interrupted.
So, I assume that there is a function my_sem_acquire:
function my_sem_acquire($key, $max_acquire = 1, $perm = 0666,
$auto_release = true) {
$id = sem_get($key, $max_acquire, $perm, $auto_release);
sem_acquire();
return $id;
}
None of instructions in function above can be interrupted.
And finally correct example:
$id = my_sem_acquire(SEMKEY);
CRITICAL REGION
my_sem_release($id);
It's the best solution, without danger of operating on not existing
semaphores. Also, unused semaphores are automaticcally removed. The
problem is, that functions my_sem_acquire and my_sem_release can't be
witten in PHP so it must be done in C inside source of PHP.Wojciech Malota