/*
** MadThreads (Easy threading with async messaging)
** Copyright (C) 2000 Gurer Ozen <madcat@linuxfan.com>
**
** This code is free software; you can redistribute it and/or
** modify it under the terms of GNU General Public License.
*/

#include <sys/types.h>

#include <proto/exec.h>
#include <exec/ports.h>
#include <exec/tasks.h>
#include <exec/semaphores.h>

#ifndef MADCAT_THREAD_H
#define MADCAT_THREAD_H

extern u_long mt_sigmask;

struct mthread_s;
typedef void (*mtcb)(struct mthread_s *t, int com, APTR data);

typedef struct mtmsg_s
{
	struct Message header;
	struct mthread_s *sender;
	int com;
	APTR data;
	int isreply;
} mtmsg;

typedef struct mthread_s
{
	struct mthread_s *next;
	struct mthread_s *prev;
	struct Task *task;
	mtcb handler;
	/* critical section :P */
	struct SignalSemaphore lock;
	int state;
	struct MsgPort *port;
	/* thread's initial args */
	struct Task *father;
	struct MsgPort *mother;
	APTR data;
} mthread;

#define MT_NEW 0
#define MT_READY 1
#define MT_DONE 2
#define MT_FREE 3


#ifdef __MORPHOS__
#define THREAD_DECL(x) struct EmulLibEntry x
#define THREAD(x) \
	static void x ## _gate(void); \
	struct EmulLibEntry x = { \
	TRAP_LIB, 0, (void (*)(void)) & x ## _gate }; \
	static void x ## _gate(void)
#else
#define THREAD_DECL(x) void SAVEDS ASM x (void)
#define THREAD(x) void SAVEDS ASM x (void)
#endif


/* setup&cleanup funcs */
extern int mt_setup(void);
extern void mt_cleanup(void);
extern void mt_listen(void);

/* launching&messaging funcs */
extern mthread *mt_run(void (*func)(void), APTR data, mtcb handler);
extern void mt_message(mthread *t, int com, APTR data);

/* functions for threads */
extern mthread *mt_start(void);
extern void mt_end(mthread *t);
extern void mt_feedback(mthread *t, int com, APTR data);



#endif	/* MADCAT_THREAD_H */
