/**********************************************************************
 
	Copyright (C) 2003-2004
	Hirohisa MORI <joshua@nichibun.ac.jp>
	Tomoki SEKIYAMA <sekiyama@yahoo.co.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/



#include "v/VSemaphore.h"

extern "C" {
#include "lock_level.h"
#include "pri_level.h"
#include "utils.h"
#include "task.h"

int get_tid();
void er_panic(char * str);
}

int lock_count;

VSemaphore::VSemaphore()
{
	v_lock = new_lock(LL_VOBJECT);
	lock_cnt = 0;
	locking_tid = 0;
}

VSemaphore::~VSemaphore()
{
	if ( locking_tid != 0 )
		er_panic("~VSemaphore");
	close_lock(v_lock);
	v_lock.so = 0;
}

void
VSemaphore::lock(char * __f,int __l)
{
int pri;
	int tid = get_tid();
	if ( locking_tid && locking_tid == tid ) // already locked
		lock_cnt++;
	else {
		pri = push_pri(PRI_TOOLKIT);
		_i_lock_task(v_lock,__f,__l); // lock here
		locking_tid = tid;
		lock_pri = pri;
	}
}

extern "C" void er_panic(char*);

void
VSemaphore::unlock()
{
int pri;
	if ( lock_cnt == 0 && locking_tid == 0 )
		er_panic("unlock unlock lock");
	if ( lock_cnt && locking_tid && locking_tid == get_tid() ) // still locked
		lock_cnt--;
	else {
		locking_tid = 0;
		pri = lock_pri;
		unlock_task(v_lock,"VObject::vobject_lock"); // unlock here
		change_pri(0,pri);
	}
}

int
VSemaphore::is_locked()
{
	if ( locking_tid == get_tid() )
		return 1;	// this thread locked this
	else if ( locking_tid )
		return -1;	// another thread locked this
	return 0;		// is not locked
}
