0

I need mutual exclusion for some operation. On my server I have APC installed.

Is there any approved Class to acquire and release a mutex ? I would avoid to reinvent the wheel if there is already an "official" solution.

Please note, I know I could use flock, but I don't want to fall back to file system to acquire a mutex

Something like:

$m = new Mutex;
$m->lock();
  //> Do stuff
$m->unlock();
  • This has been answered before: http://stackoverflow.com/questions/2921469/php-mutual-exclusion-mutex – Mr. Llama Dec 11 '12 at 21:50
  • I upvoted that question. But the answer doesn't answer this. (he uses sem) –  Dec 11 '12 at 21:58

3 Answers3

1

Later versions of PHP have a Mutex class built-in. If you are on a *nix system, also look for the "Semaphore Functions" in the documentation.

Mark Leighton Fisher
  • 5,609
  • 2
  • 18
  • 29
  • I wouldn't use sempahore. I only need Mutex. Could you post an example of Mutex class? Doc is pretty vague – dynamic Dec 11 '12 at 21:59
1

You might want to try my Mutex implementation in php. It supports several adapters - flock, memcache, mysql. There is currently no apc implementation as there is no way to use it across multiple web servers - but you might always easily add it and send pull request.

https://github.com/arvenil/ninja-mutex

Kamil Dziedzic
  • 4,721
  • 2
  • 31
  • 47
0

It is usually a nosense to implement mutex library with APC. The most useful application of Mutex/Locks is for distributed environments and multi instance... but APC is local to the machine.

To implement a reliable multi-instance Mutex signaling in a distributed DB you will need to use FileSystem (S3) or a shared REDIS or MEMCACHED service (a DB can do de work but is slower).

Ninja Mutex implementation is not recommended for distributed environments.

Istead use this library: https://github.com/cheprasov/php-redis-lock It was tested by me and works fine with multiple PHP-FPM instances, Redis and MongoDB cluster.

If you want more information please read official redis documentation about this: https://redis.io/topics/distlock

manuelbcd
  • 3,106
  • 1
  • 26
  • 39