//                              -*- 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.
//
// thread.c --
//
// Author           : Thierry Delisle
// Created On       : Tue Jan 17 12:27:26 2017
// Last Modified By : Thierry Delisle
// Last Modified On : --
// Update Count     : 0
//

#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 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();
	this_processor->current_coroutine = thrd_c;

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

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

	ScheduleThread(thrd_h);
}

void yield( void ) {
	ScheduleInternal( this_processor->current_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 = 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_processor->current_coroutine = dst;
	CtxSwitch( src->stack.context, dst->stack.context );
	this_processor->current_coroutine = src;

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

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