mutex Provides a locking mechanism with timeout functionality

This extension can be used in case a certain part of your application should only run ONCE at a time. For example you may have a cronjob console command that is executed every minute regardless of how long the action in the cronjob takes. See Mutex article on Wikipedia.

// Check if we have a lock already. If not set one which// expires automatically after 10 minutes.if (Yii::app()->mutex->lock('some-unique-id', 600))
{
// Do some time-expensive stuff here...// sleep(10) as example// and after that release the lock...
Yii::app()->mutex->unlock();
}
else
{
// The lock does already exist so we exitecho"Already working on it...";
exit;
}

The $timeout variable is there to ensure that the lock isn't infinite in case of things like a server crash. Means if you don't define a timeout and unlock() isn't called for some reason, the lock will stay forever.

All locks are represented in a single file. You can change the $mutexFile variable to change the path of this file (defaults to the Yii runtime path + /mutex.bin).

You can also define an $id when unlocking. That means in one cronjob you could setup a lock and in another one you could release that lock. For local created locks (current request), only unlock() works to make sure nested locks will get released in order.

Some more usage examples:

// Waiting for a lock to get released (spin lock)// Make sure to call sleep() inside of the loop, because everytime// you call lock(), the $mutexFile gets read (physical file-access).while (!Yii::app()->mutex->lock('id'))
{
sleep(1);
}
...
Yii::app()->mutex->unlock();

Downloads

If your app uses MySQL database, better use MySQL named locks for that. They will unlock automatically if your thread or even the entire server happens to die prematurely, so there's no need to set a timeout. Just make sure your lock's name is unique throughout the entire MySQL server (which is not very difficult to achieve).

when exception happens from the locked code segment , what 's your advise?

// Check if we have a lock already. If not set one which// expires automatically after 10 minutes.if (Yii::app()->mutex->lock('some-unique-id'))
{
// Do some time-expensive stuff here...// sleep(10) as examplethrownewException('for test !');
trigger_error('for test too!');
// and after that release the lock...
Yii::app()->mutex->unlock();
}
else
{
// The lock does already exist so we exitecho"Already working on it...";
exit;
}

you see if there happens some error or trigger exception , the unlock will never called !