You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@apr.apache.org by Daniel May <da...@spryware.com> on 2005/11/21 02:58:43 UTC

RE: Cross Process Mutex

The solution we used was specific to the pthreads mutex implementation.
I am not sure what the formal definitions of proc and global mutex's are
in the scope of APR, but I needed a global mutex that would hold across
two or more independent processes.

We chose the shared memory route using pthreads.  Here is a code
snippet:

typedef struct _SHARED_MUTEX_HEADER  
{
	pthread_mutex_t  m_mutex;
	uint32_t	instanceCount;
	unsigned	pid;
	bool		isValid;
} SHARED_MUTEX_HEADER;

SHARED_MUTEX_HEADER *CreateMutex(char *name)
{
            
            SHARED_MUTEX_HEADER *pMem = shm_alloc_ptr(name);
		pthread_mutexattr_t  attr;	

		::pthread_mutexattr_init(&attr);
		::pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE);
	
if(0!=::pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED))
			m_valid = false;
		else if(0==::pthread_mutex_init(&pMem->m_mutex, &attr))
			m_valid = true;
		else
			m_valid = false;

		::pthread_mutexattr_destroy(&attr);
		pMem->isValid = m_valid;
            return pMem;
}

Of course, this is pseudo code, assuming you have something called
shm_alloc_ptr() that returns a pointer to shared mem.
We are using the APR apr_shm_* calls for this.


There is also the possiblility that that mutex will get orphaned if the
process who last took ownership of the shared memory dies, so we added
the pid to the structure so we can verify if the current owner of the
mutex is still alive.

int TryMutex(SHARED_MUTEX_HEADER *pMem)
{
	if(::pthread_mutex_trylock(&pMem->m_mutex) == EBUSY)
	{
		if(IsAlive(pMem->pid) == false)
			return RETURN_CODE_ABANDONED;		
            if(::pthread_mutex_trylock(&pMem->m_mutex) == EBUSY)
			return RETURN_CODE_FAILURE;
	}
	
	pMem->pid = getpid();
	return RETURN_CODE_SUCCESS;

}
 

-----Original Message-----
From: cbrazvan@laitek.com [mailto:cbrazvan@laitek.com] 
Sent: Sunday, November 20, 2005 3:46 PM
To: Daniel May
Subject: Cross Process Mutex

Hello Daniel.

First of all, I hope you will indulge my intrusion and will forgive me
for contacting you directly.

I am having exactly the same problem you describe on APR-dev mailing
list:
developing name based cross-process locking on *nix systems.
I'm trying to figure this one out for several hours now and all my hopes
are shattered.

One of the posts there was proposing a shared-memory based mutex-lookup
mechanism, which was what I originally thought I needed to do.
Using file-based locks would be another approach, but trusting the
file-system doing a good job on this in a time-critical environment
would probably be foolish.

Have you found a good, simple solution to this?

Thank you and best regards,
Razvan