Skip to content

Socket finalizer is slightly more expensive than necessary #66

@treeowl

Description

@treeowl

socket installs its finalizer using

           _ <- mkWeakMVar mfd (close s)

This produces a weak reference connecting the MVar# to the MVar, which forces the MVar box to be allocated and retained even if the Socket will actually be unboxed for all other purposes. To avoid this, you really want the (deprecated, for some reason) function addMVarFinalizer. Since it's deprecated, just implement it yourself:

-- |Add a finalizer to an 'MVar' (GHC only).  See "Foreign.ForeignPtr" and
-- "System.Mem.Weak" for more about finalizers.
addMVarFinalizer :: MVar a -> IO () -> IO ()
addMVarFinalizer (MVar m) (IO finalizer) =
    IO $ \s -> case mkWeak# m () finalizer s of { (# s1, _ #) -> (# s1, () #) }

Side note: primitive-unlifted offers addFinalizerUnlifted :: PrimUnlifted k => k -> IO () -> IO (), which would be perfect, but that's a dependency with some very stringent lower bounds so I doubt you'll want to use it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions