/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/



#define STREAM_LIB

#include	<signal.h>
#include	<errno.h>
#include	"task.h"
#include	"stream.h"
#include	"lock_level.h"
#include	"machine\\s_thread.h"
#include	"utils.h"

extern SEM stream_lock;

void sigusr1_handler(int dmy);

STREAM * close_stream;

void
close_sync_func();

void
init_machine_stream()
{
	new_tick(close_sync_func,2,0);
	/* signal(SIGUSR1,sigusr1_handler); */
	signal(1,sigusr1_handler);
}

void sigusr1_handler(int dmy)
{
	if ( signal(1, sigusr1_handler) < 0 ){
		printf("USR %i %i error %i\n", get_tid(),getpid(),errno);
/*		printf("USR %i %i error %i\n", GetCurrentThreadId(), GetCurrentProcessId(),errno); */
	}
}

/*
void
_s_insert_thread(STREAM * s,S_FILE_THREAD * t)
{
	t->tid = get_tid();
	t->next = s->h.thread;
	s->h.thread = t;
}

void
s_delete_thread(STREAM * s,S_FILE_THREAD * t)
{
S_FILE_THREAD ** tp;

	lock_task(stream_lock);
	for ( tp = &s->h.thread ; *tp ; tp = &(*tp)->next )
		if ( *tp == t ) {
			*tp = t->next;
			break;
		}
	if ( s->h.tbl == 0 )
		wakeup_task((int)&s->h.thread);
	unlock_task(stream_lock,"s_delete_thread");
}
*/
void
close_sync_func()
{
	lock_task(stream_lock);
	if ( close_stream )
		wakeup_task((int)&close_stream->h.thread);
	unlock_task(stream_lock,"close_sync_func");
}


void
_s_close_sync(STREAM * s)
{
	for ( ; close_stream ; ) {
		sleep_task((int)&close_stream,stream_lock);
		lock_task(stream_lock);
	}
	close_stream = s;

	for ( ; ; ) {
		if ( s->h.thread == 0 )
			break;
/*
		pthread_kill(s->h.thread->tid,SIGUSR1);
*/		sleep_task((int)&s->h.thread,stream_lock);
		lock_task(stream_lock);
	}
	close_stream = 0;
	wakeup_task((int)&close_stream);
}
