I have problem using semaphores in my Yii program. What I would like to achieve is to use semaphores to ensure that I do not encounter race condition with a particular cache entry. This is a sample prototype of an increasing counter which will +1 on reload and the value stored in cache.
This is what my code looks like:
// in a controller
public function actionIndex()
{
$lockRef = 20001;
$count = Yii::app()->cache->get('counter');
if ($count == FALSE) {
$count = 1;
Yii::app()->cache->set('counter', $count);
}
$lockKey = $this->getLock($lockRef);
$count = Yii::app()->cache->get('counter');
$count = $count+1;
Yii::app()->cache->set('counter', $count);
$this->releaseLock($lockKey);
echo $count;
}
private function getLock($lockKey)
{
// this works ----------------
while(Yii::app()->cache->get('lock-'.$lockKey)) {
usleep(20000);
}
Yii::app()->cache->set('lock-'.$lockKey, TRUE);
return $lockKey;
// this does not work ----------------
$lockKey = sem_get($lockKey, 1);
sem_acquire($lockKey);
return $lockKey;
}
private function releaseLock($lockKey)
{
// this works ----------------
Yii::app()->cache->set('lock-'.$lockKey, FALSE);
// this does not work ----------------
sem_release($lockKey);
}
If you have a look at getLock() and releaseLock() there are 2 parts, a part that works for me and another that doesn’t. The part that works creates a lock by using a variable in cache - I do not fancy this implementation and would prefer the usage of semaphores. However, the semaphores does not actually lock the critical section. Anyone has any idea?
Thank you.