#include <err.h>
#include <sys/types.h>
#include <os/Mutex.h>
#include <os/Thread.h>
#include <kernel/AutoSpinlock.h>

namespace OS {

Mutex::Mutex()
	: mHolder(0),
	mDispatcher(true)
{
}

Mutex::~Mutex()
{
	// It's totally illegal to delete an active mutex
	ASSERT(mHolder == 0);
}

status_t Mutex::Acquire()
{
	mDispatcher.WaitOn(true);
	mHolder = Thread::GetCurrent();
	return NO_ERROR;
}

status_t Mutex::Release()
{
	if (Thread::GetCurrent() != mHolder)
		panic("Mutex::Release: Thread %p trying to release mutex %p owned by %p\n",
				Thread::GetCurrent(), this, mHolder);
	mHolder = 0;
	mDispatcher.Pulse(true);
	return NO_ERROR;
}

} // namespace OS

