//                              -*- Mode: CFA -*-
//
// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// monitor.c --
//
// Author           : Thierry Delisle
// Created On       : Thd Feb 23 12:27:26 2017
// Last Modified By : Thierry Delisle
// Last Modified On : --
// Update Count     : 0
//

#include "monitor"

#include "kernel_private.h"

void enter(monitor * this) {
	lock( &this->lock );
	thread * thrd = this_thread();

	if( this->holder ) {
		append( &this->entry_queue, thrd );
		ScheduleInternal( &this->lock );
		return;
	}
	else {
		this->holder = thrd;
	}

	unlock( &this->lock );
}

void leave(monitor * this) {
	lock( &this->lock );

	thread * thrd = this_thread();
	assert( thrd == this->holder );

	this->holder = pop_head( &this->entry_queue );

	unlock( &this->lock );

	if( this->holder ) ScheduleThread( this->holder );
}