OCamlPro / flambda-task-force

13 stars 1 forks source link

Interaction with finalization #165

Open mmottl opened 8 years ago

mmottl commented 8 years ago

This may not be an actual issue but could be a potential one so I'd like to make sure this is noted somewhere. Consider the following code:

type t = { foo : foo }

let handle_t mtx t = Mutex.critical_section mtx ~f:(fun () -> handle_foo t.foo)

If t has a finalizer, accessing t.foo within the lock should guarantee that t is still around while the mutex is locked. This may be necessary if the finalizer, too, makes use of the lock. But foo is immutable so an overly clever optimization might decide to not hold on to t, extracting foo before the mutex is locked. I think such optimizations should be avoided (maybe they already are).

Making foo a mutable record field would presumably prevent such an optimization in any case, but may not reflect the user's intention of keeping the field immutable.

mmottl commented 8 years ago

Maybe such complicated semantics should better be reflected more declaratively in the user code. I guess one could add a primitive to the Gc module in the standard library for that, e.g.:

  external keep_until_now : _ -> unit = "%keep_until_now"

The only effect would be to force a potential optimizer to keep the value registered with the GC until at least Gc.keep_until_now is called on the value.