Semaphores to avoid critical task collision

Standard

This is a sample from my cakephp shell script that has some critical processing. It is ran every second and sometimes the script can take over a second to process. Thus, I needed a way to avoid the script from accessing the same critical business logic and manipulating data.

The semaphore works by acquiring the key with the given id: 1068. I have set the max number of semaphores to 1 for the key. All other shell scripts that are ran will autorelease when they cannot acquire the semaphore (hence another shell script is still processing).

/**
* Semaphore values
*/
private $sema_key = 1068;
private $sema_maxAcquire = 1;
private $sema_permissions = 0666;
private $sema_autoRelease = 1;

public function main() {
// Acquire our lock
   $semaphore = sem_get($this->sema_key, $this->sema_maxAcquire, $this->sema_permissions, $this->sema_autoRelease);
   if (!$semaphore) {
      throw new InternalErrorException('Error getting semaphore');
   }
   sem_acquire($semaphore);

   // DO LOGIC: CRITICAL TASK

   // Release the semaphore for other processes
   sem_release($semaphore);
}

Leave a Reply

Your email address will not be published.