Using of semaphores with Yii

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.

and forget to add:

Yii version: 1.1.10

O/S: Ubuntu 10.04

PHP: 5.3.2

Web server: apache2

there are many possibilities why semaphores do not work - they are represented by files in filesystem, so you could provide writable path. also - what is the effect when they "do not work"? are there any error message? something in application log? php error log? apache error log?

try to create simple php script aquiring and releasing semaphore and run it from command line - check if there are any errors. try to run such script as www-data user to simulate apache environment…

Are you asking about a custom cache implementation? Since your example includes controller actions, I believe it’s not.

In any case, I’d just like to point out that most of the caching engines have this already resolved with incr() and decr() ( or similar ) functions.