Re: [APC-DEV] atomaticity/thread safeness of apc shared memory functions+mutexes

[email protected] (Exception e) Thu, 25 Dec 2008 16:25:24 +0100
Newsgroups php.apc.dev
Message-ID <[email protected]>
> apc_fetch() grabs a copy of the value in shared memory.  What you do
> with it locally in the process after the fetch is irrelevant.  It is
> just a copy.  You can then overwrite the value in shared memory with a
> new version with an apc_store() call.  Locking shared memory the way you
> suggest would be a really bad idea.  It would be a performance
> nightmare.  You need to design your code in a way that does not require
> that.
> 

Locking all shared memory would indeed be bad, I was already wondering 
whether you really meant that. But I use php for a multi-user game as 
part of an academic investigation. To speed things up I 
store(=serialize) objects in shared memory. I need to ensure that 
certain objects in shared memory keep a coherent state. That is, when I 
use object1 and object2 they should not be modified during a request. So 
then I need to lock those two entries. Atomic reads and writes won't 
help here.
But since the apc functions are themselves atomic, I could utilize them 
for implementing mutexes. A simple example would be

function lock($entry)	{
	// busy wait
	while(!apc_add($entry.'.lock'))
		sleep(1);
}

function unlock($entry)	{
	return apc_delete($entry.'.lock');
}

lock('obj1');
lock('obj2');
$obj1= apc_fetch('obj1');
$obj2 = apc_fetch('obj2');

//process, apc_store val1 and val2 again

unlock('obj1');
unlock('obj2');


Then it would only be nice if lock and unlock would be part of apc_* 
userland functions. I am curious about your ideas.