[MLton] Callback functions: how?

Vesa Karvonen vesa.karvonen at cs.helsinki.fi
Wed Feb 14 11:51:21 PST 2007


Quoting "Wesley W. Terpstra" <wesley at terpstra.ca>:

> What's the most efficient way to implement callback functions in MLton?

The most efficient method will likely depend on the context.  For example,
if a program will always only register just a single callback at
initialization time, then that can be made much faster than when an
application may dynamically register and unregister an unbounded number of
callbacks (e.g. timeouts).  The number of times the callback is called
from the C side (just once vs repeatedly thousands or even millions of
times) also makes a big difference.

As a generic solution, I'm currently using a "cache"

  http://mlton.org/cgi-bin/viewsvn.cgi/mltonlib/trunk/com/ssh/misc-util/unstable/cache.sig?view=auto

where the key type can be disguised as a pointer (note the where
constraint, and see the NLFFI c.sig)

  http://mlton.org/cgi-bin/viewsvn.cgi/mltonlib/trunk/com/ssh/misc-util/unstable/cache.sml?view=auto

Basically, there is a single exported ML callback function and a
callback cache for each imported C function that takes callbacks.
The key generated by the cache is given to the C side as the
context pointer (uarg in your snippet).

The cache is a hash table where the keys are generated by a quick and
dirty RNG.  Theoretically speaking, it should scale well (prime sized
hash table and random keys), but the hash table lookup certainly adds
some overhead.

> |'m assuming Henry has a good solution to this in his secret mGtk/ 
> MLton port. Of course, it's not in svn, so I can't look and see...

If someone knows better generic solutions then I'm all ears.

-Vesa Karvonen



More information about the MLton mailing list