I need to have a mutex method in PHP so that it keeps exclusivity by a variable value. This is that threads with same value should enter that method one at a time while threads with different values may access that method arbitrarily.
For example, given that method:
/**
* @param integer $value
*/
function mutexMethod($value)
{
// Lock for value $value
echo 'processing';
sleep(2);
echo 'this is so heavy';
// Unlock for value $value
}
For example (I need this to be run through apache):
time |
0 | php > mutexMethod(1); | php > mutexMethod(2); | php > mutexMethod(1);
1 | processing | processing |
2 | | |
3 | this is so heavy | this is so heavy | processing
4 | | |
5 | | | this is so heavy
As a first solution, I've tried using semaphores but since $value may get any value, I've run out of semaphores space very quickly (I've tried removing the semaphores after using them but this breaks other threads waiting for it and since I cannot know if there are any threads waiting for them, I cannot remove them arbitrarily.
As a second solution, I've tried creating a file with the value $value as name and using flock to lock any other thread. Despite this worked in the CLI, I couldn't manage to make it work through apache. It certainly locked the file but it never released that lock so any other request got stuck until the first one timed out (after 30 seconds).
Finally I though about using MySQL locks but I would like to avoid them as much as we would like to not use the MySQL instance for such things. Ideally we would like a pure PHP solution.
Do you have an idea on how can I solve that problem? I would like to avoid single-semaphore solutions (like having a single semaphore to control access to a file where to keep track of the locks) as this would create a massive bottleneck (specially for those threads with different values).
Thank you very much.

$values.