rvmutex_.c

来自「h.248协议源码」· C语言 代码 · 共 100 行

C
100
字号
#if (0)
******************************************************************************
Filename    :
Description : Recursive mutex implementation
******************************************************************************
                Copyright (c) 1999 RADVision Inc.
************************************************************************
NOTICE:
This document contains information that is proprietary to RADVision LTD.
No part of this publication may be reproduced in any form whatsoever 
without written prior approval by RADVision LTD..

RADVision LTD. reserves the right to revise this publication and make 
changes without obligation to notify any person of such revisions or 
changes.
******************************************************************************
$Revision:$
$Date:$
$Author: S. Cipolli$
******************************************************************************
#endif

#include <assert.h>
#include <stdio.h>		/* Require for assert macro in PSOS */
#include <stddef.h>
#include "rvplatform.h"
#include "rvmutex_.h"

#if defined(RV_MUTEX_POSIX) 
RvMutex_* rvMutexConstruct_(RvMutex_* m) {
	pthread_mutexattr_t ma;
	pthread_mutexattr_init(&ma);
	pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);
	pthread_mutex_init(m, &ma);
	pthread_mutexattr_destroy(&ma);
	return m;
}
#elif defined(RV_MUTEX_REDHAT)
RvMutex_* rvMutexConstruct_(RvMutex_* m) {
	pthread_mutexattr_t ma;
	pthread_mutexattr_init(&ma);
	pthread_mutexattr_setkind_np(&ma, PTHREAD_MUTEX_RECURSIVE_NP);
	pthread_mutex_init(m, &ma);
	pthread_mutexattr_destroy(&ma);
	return m;
}
#elif defined(RV_MUTEX_GENERIC)
RvMutex_* rvMutexConstruct_(RvMutex_* m) {
	rvSemConstruct_(&m->lock, 1);
	rvSemConstruct_(&m->handle, 0);
	m->owner = 0;
	m->count = 0;
	m->waiters = 0;
	return m;
}

void rvMutexDestruct_(RvMutex_* m) {
	rvSemDestruct_(&m->handle);
	rvSemDestruct_(&m->lock);
}

void rvMutexLock_(RvMutex_* m) {
	RvThreadId current = rvThreadIdCurrent();

	rvSemWait_(&m->lock);

	if (rvThreadIdEqual(m->owner, RV_THREADID_NONE))
		rvThreadIdCopy(m->owner, current);
	else if (!rvThreadIdEqual(m->owner, current)) {
		++(m->waiters);
		rvSemPost_(&m->lock);	
		rvSemWait_(&m->handle);	/* m->lock is locked when we return */	
		rvThreadIdCopy(m->owner, current);
		--(m->waiters);
	}
	++(m->count); 		
	rvSemPost_(&m->lock);
}

void rvMutexUnlock_(RvMutex_* m) {
	rvSemWait_(&m->lock);

	/* Make sure unlocking thread is owner and count is not zero */
	assert(rvThreadIdEqual(m->owner, rvThreadIdCurrent()));
	assert(m->count);

	--(m->count);
	if (m->count == 0) {
		rvThreadIdCopy(m->owner, RV_THREADID_NONE);
		if (m->waiters > 0)
			rvSemPost_(&m->handle);
		else
			rvSemPost_(&m->lock);				
	} else
		rvSemPost_(&m->lock);	
}

#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?