//                              -*- 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 --
//
// Author           : Thierry Delisle
// Created On       : Tue Jan 17 12:27:26 2017
// Last Modified By : Peter A. Buhr
// Last Modified On : Thu Jul 20 15:22:24 2017
// Update Count     : 1
//

#ifndef THREADS_H
#define THREADS_H

#include <assert.h>
#include "invoke.h"

#include "coroutine"
#include "monitor"

//-----------------------------------------------------------------------------
// Coroutine trait
// Anything that implements this trait can be resumed.
// Anything that is resumed is a coroutine.
trait is_thread(dtype T) {
      void ^?{}(T* mutex this);
      void main(T* this);
      thread_desc* get_thread(T* this);
};

#define DECL_THREAD(X) thread_desc* get_thread(X* this) { return &this->__thrd; } void main(X* this)

forall( dtype T | is_thread(T) )
static inline coroutine_desc* get_coroutine(T* this) {
	return &get_thread(this)->cor;
}

forall( dtype T | is_thread(T) )
static inline monitor_desc* get_monitor(T * this) {
	return &get_thread(this)->mon;
}

static inline coroutine_desc* get_coroutine(thread_desc * this) {
	return &this->cor;
}

static inline monitor_desc* get_monitor(thread_desc * this) {
	return &this->mon;
}

extern volatile thread_local thread_desc * this_thread;

forall( dtype T | is_thread(T) )
void __thrd_start( T* this );

//-----------------------------------------------------------------------------
// Ctors and dtors
void ?{}(thread_desc* this);
void ^?{}(thread_desc* this);

//-----------------------------------------------------------------------------
// thread runner
// Structure that actually start and stop threads
forall( dtype T | sized(T) | is_thread(T) )
struct scoped {
	T handle;
};

forall( dtype T | sized(T) | is_thread(T) | { void ?{}(T*); } )
void ?{}( scoped(T)* this );

forall( dtype T, ttype P | sized(T) | is_thread(T) | { void ?{}(T*, P); } )
void ?{}( scoped(T)* this, P params );

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

void yield();
void yield( unsigned times );

#endif //THREADS_H

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