/*=====================================================================*/
/*    serrano/prgm/project/bigloo/fthread/src/Java/BglAsync.java       */
/*    -------------------------------------------------------------    */
/*    Author      :  Manuel Serrano                                    */
/*    Creation    :  Mon Feb 11 13:45:20 2002                          */
/*    Last change :  Sun Nov 16 15:00:24 2003 (serrano)                */
/*    Copyright   :  2002-03 Manuel Serrano                            */
/*    -------------------------------------------------------------    */
/*    A class implementing asynchronous thread. An asynchronous thread */
/*    is implemented by the means of a Java thread that permantenly    */
/*    execute a thunk.                                                 */
/*=====================================================================*/

/*---------------------------------------------------------------------*/
/*    The package                                                      */
/*---------------------------------------------------------------------*/
package bigloo.fairthread;
import java.lang.*;
import bigloo.*;

/*---------------------------------------------------------------------*/
/*    BglAsync                                                         */
/*---------------------------------------------------------------------*/
public class BglAsync extends Thread {
   private procedure thunk;
   private Object id;
   private BglThread scdl;
   
   // public constructor
   public BglAsync( BglThread s, procedure proc, Object i ) {
      super();
      scdl = s;
      thunk = proc;
      id = i;
      start();
   }

   // The thread entry-point
   public void run() {
      try {
	 thunk.funcall0();
      } catch( Throwable e ) {
	 try {
	    foreign.internalerror( e );
	 } catch( Throwable _ ) {
	    System.exit( 1 );
	 }
      }
   }
      
   // Scheduler wait for an asynchronous event. This function must
   // always be called within the dynamic extent of a bglasync_synchronize   
   public static void scheduler_wait( BglThread scdl ) {
      try {
	 scdl.wait();
      } catch( Throwable e ) {
	 try {
	    foreign.internalerror( e );
	 } catch( Throwable _ ) {
	    System.exit( 1 );
	 }
      }
   }

   // Notify a Scheduler of an asynchronous event. This function must
   // always be called within the dynamic extent of a bglasync_synchronize   
   public static void scheduler_notify( BglThread scdl ) {
      scdl.notify();
   }

   // synchronized block
   public static Object synchronize( BglThread scdl, procedure proc ) {
      synchronized( scdl ) {
	 return proc.funcall0();
      }
   }
}   
