提供的答案很好,文件锁效果很好,但是,由于您使用的是 MySQL,我想我也会回答。使用 MySQL,您可以使用GET_LOCK和RELEASE_LOCK实现协作异步锁定。
*免责声明:以下示例未经测试。我之前已经成功地实现了一些非常接近这个的东西,下面是大致的想法。
假设您已将此 GET_LOCK 函数包装在名为 Mutex 的 PHP 类中:
class Mutex {
private $_db = null;
private $_resource = '';
public function __construct($resource, Zend_Db_Adapter $db) {
$this->resource = $resource;
$this->_db = $db;
}
// gets a lock for $this->_resource; you could add a $timeout value,
// to pass as a 2nd parameter to GET_LOCK, but I'm leaving that
// out for now
public function getLock() {
return (bool)$this->_db->fetchOne(
'SELECT GET_LOCK(:resource)',
array(
':resource' => $this->_resource
));
}
public function releaseLock($resource) {
// using DO because I really don't care if this succeeds;
// when the PHP process terminates, the lock is released
// so there is no worry about deadlock
$this->_db->query(
'DO RELEASE_LOCK(:resource)',
array(
':resource' => $resource
));
}
}
在 A() 从表中获取方法之前,让它请求锁。您可以使用任何字符串作为资源名称。
class JobA {
public function __construct(Zend_Db_Adapter $db) {
$this->_db = $db;
}
public function A() {
// I'm assuming A() is a class method and that the class somehow
// acquired access to a MySQL database - pretend $this->db is a
// Zend_Db instance. The resource name can be an arbitrary
// string - I chose the class name in this case but it could be
// 'barglefarglenarg' or something.
$mutex = new Mutex($this->db, get_class($this));
// I choose to throw an exception but you could just as easily
// die silently and get out of the way for the next process,
// which often works better depending on the job
if (!$mutex->getLock())
throw new Exception('Unable to obtain lock.');
// Got a lock, now select the rows you need without fear of
// any other process running A() getting the same rows as this
// process - presumably you would update/flag the row so that the
// next A() process will not select the same row when it finally
// gets a lock. Once we have our data we release the lock
$mutex->releaseLock();
// Now we do whatever we need to do with the rows we selected
// while we had the lock
}
}
当您设计多个进程选择和修改相同数据的场景时,这种事情会非常方便。使用 MySQL 时,为了可移植性,我更喜欢这种数据库方法而不是文件锁定机制 - 如果锁定机制在文件系统外部,则更容易在不同平台上托管您的应用程序。当然可以,而且效果很好,但是根据我的个人经验,我发现这更容易使用。
如果您计划将您的应用程序跨数据库引擎移植,那么这种方法可能不适合您。