//
// 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.
//
// thread.c --
//
// Author           : Thierry Delisle
// Created On       : Tue Jan 17 12:27:26 2017
// Last Modified By : Peter A. Buhr
// Last Modified On : Fri Jul 21 22:34:46 2017
// Update Count     : 1
//

#include "thread"

#include "kernel_private.h"
#include "libhdr.h"

#define __CFA_INVOKE_PRIVATE__
#include "invoke.h"

extern "C" {
	#include <fenv.h>
	#include <stddef.h>
}

extern volatile thread_local processor * this_processor;

//-----------------------------------------------------------------------------
// Thread ctors and dtors

void ?{}(thread_desc& this) {
	(this.cor){};
	this.cor.name = "Anonymous Coroutine";
	this.mon.owner = &this;
	this.mon.recursion = 1;
	this.next = NULL;

	this.current_monitors      = &this.mon;
	this.current_monitor_count = 1;
}

void ^?{}(thread_desc& this) {
	^(this.cor){};
}

forall( dtype T | sized(T) | is_thread(T) | { void ?{}(T&); } )
void ?{}( scoped(T)& this ) {
	(this.handle){};
	__thrd_start(this.handle);
}

forall( dtype T, ttype P | sized(T) | is_thread(T) | { void ?{}(T&, P); } )
void ?{}( scoped(T)& this, P params ) {
	(this.handle){ params };
	__thrd_start(this.handle);
}

forall( dtype T | sized(T) | is_thread(T) )
void ^?{}( scoped(T)& this ) {
	^(this.handle){};
}

//-----------------------------------------------------------------------------
// Starting and stopping threads
forall( dtype T | is_thread(T) )
void __thrd_start( T& this ) {
	coroutine_desc* thrd_c = get_coroutine(this);
	thread_desc*  thrd_h = get_thread   (this);
	thrd_c->last = this_coroutine;

	// LIB_DEBUG_PRINT_SAFE("Thread start : %p (t %p, c %p)\n", this, thrd_c, thrd_h);

	disable_interrupts();
	create_stack(&thrd_c->stack, thrd_c->stack.size);
	this_coroutine = thrd_c;
	CtxStart(&this, CtxInvokeThread);
	assert( thrd_c->last->stack.context );
	CtxSwitch( thrd_c->last->stack.context, thrd_c->stack.context );

	ScheduleThread(thrd_h);
	enable_interrupts( DEBUG_CTX );
}

void yield( void ) {
	BlockInternal( this_thread );
}

void yield( unsigned times ) {
	for( unsigned i = 0; i < times; i++ ) {
		yield();
	}
}

void ThreadCtxSwitch(coroutine_desc* src, coroutine_desc* dst) {
	// set state of current coroutine to inactive
	src->state = src->state == Halted ? Halted : Inactive;
	dst->state = Active;

	//update the last resumer
	dst->last = src;

	// set new coroutine that the processor is executing
	// and context switch to it
	this_coroutine = dst;
	assert( src->stack.context );
	CtxSwitch( src->stack.context, dst->stack.context );
	this_coroutine = src;

	// set state of new coroutine to active
	dst->state = dst->state == Halted ? Halted : Inactive;
	src->state = Active;
}

// Local Variables: //
// mode: c //
// tab-width: 4 //
// End: //
