[MLton-devel] calling SML from C; reentrance

Stephen Weeks MLton@mlton.org
Fri, 16 May 2003 14:48:57 -0700


There is still a correctness problem with all of the proposed
solutions.  The problem happens during the window when the C Handler
is starting to handle the C call but is not yet ready to handle
another C call -- in a multi-threaded program a thread switch could
switch to another thread that makes a C call, switching to the C
handler thread in a bogus state.  The best solution that I can see is
to make the setup of the C handler a critical section, ending the
critical section only when the C handler is ready again.

val setCallFromCHandler =
   let
      val r: (unit -> unit) ref =
	 ref (fn () => raise Fail "no handler for C calls")
      val _ =
	 Prim.setCallFromCHandler
	 (toPrimitive
	  (new (let
		   fun loop (): unit =
		      let
			 val t = Prim.saved ()
			 val _ =
			    Prim.switchTo
			    (toPrimitive
			     (new (fn () => (atomicEnd ()
					     ; !r ()
					     ; Prim.setSaved t
					     ; Prim.returnToC ()))))
		      in
			 loop ()
		      end
		in
		   loop
		end)))
   in
      fn f => r := f
   end

And MLton_callFromC does s->canHandle++.


-------------------------------------------------------
This SF.net email is sponsored by: If flattening out C++ or Java
code to make your application fit in a relational database is painful, 
don't do it! Check out ObjectStore. Now part of Progress Software.
http://www.objectstore.net/sourceforge
_______________________________________________
MLton-devel mailing list
MLton-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/mlton-devel