Skip to content

API to prevent automatic Gc collection #8794

@toots

Description

@toots

Hi,

I apologize if this has already been discussed but we've been running into a pretty intractable issue with the Gc recently which I believe could be solved elegantly with an API to temporarily disable automatic Gc collection.

Here's a naive example pretty close to our case:

let logs = Queue.create ()
let m = Mutex.create ()

(* Queue log *)
let log msg =
  Mutex.lock m;
  Queue.add msg logs;
  Mutex.unlock m

(* Print logs *)
let print () =
  Mutex.lock m;
  Queue.iter print_log logs;
  Mutex.unlock m

let create_big_object id =
  let finalise () =
    log ("Object  " ^ id ^ " cleaned up!")
  in
  let s =  (...) in
  Gc.finalise_last finalise s;
  s 

What can happen here is a deadlock inside a thread calling any of the log or print functions. Indeed, if the Gc starts a collection on a value instantiated via create_big_object then we may run into a double-locking of the same mutex.

This example is naive but, in a large scale application, tracking down every call that may be executed inside a finalise callback can be pretty difficult.

It is possible to write complex wrappers about those operations to make it work but I believe that this kind of issue is bound to happen in many other cases where the user writes some blocking code not knowing that the Gc might interrupt it and run into a double locking situation.

On the other hand, being able to assure that the Gc will not interrupt the execution would guarantee an elegant and easy to check solution. Something like:

let log = Gc.suspend (fun msg ->
  Mutex.lock m;
  Queue.add msg logs;
  Mutex.unlock m)

(* Print logs *)
let print = Gc.suspend (fun () ->
  Mutex.lock m;
  Queue.iter print_log logs;
  Mutex.unlock m)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions