mutualExclusion.php 1.15 KB
<?php

require_once dirname(__FILE__) . '/../config.php';
require_once LIBDIR . 'errException.php';


function acquireLock ($lockFile, $csId)
{
	$fName = $lockFile . $csId . '.lck';
	$lock  = NULL;

	setErrExceptionMapping ();

	$lockHandle = fopen ($fName, 'w');

	// if available use semaphores for mutual exclusion because flock
	// doesn't work reliably in threaded environments.
	if (function_exists ('sem_get'))
	{
		$lock = sem_get (ftok ($fName, $csId), 1, 0644, TRUE);

		$state = sem_acquire ($lock);
		while ($state === FALSE)
			$state = sem_acquire ($lock);
	}
	else
	{
		$state = flock ($lock, LOCK_EX);
		while ($state === FALSE)
			$state = flock ($lock, LOCK_EX);
	}

	// Here one could write informations in the lockfile...time, pid, etc.
	fwrite ($lockHandle, session_id () . '::' . time ());
	fflush ($lockHandle);

	resetErrExceptionMapping ();

	$userAbort = ignore_user_abort(TRUE);
	return array ($lockHandle, $lock, $userAbort);
}

function releaseLock ($lock)
{
	setErrExceptionMapping ();

	if ($lock[1] !== NULL)
		sem_release ($lock[1]);

	ftruncate ($lock[0], 0);
	fclose ($lock[0]);

	resetErrExceptionMapping ();

	ignore_user_abort($lock[2]);
}

?>