haskell-socket icon indicating copy to clipboard operation
haskell-socket copied to clipboard

Socket finalizer is slightly more expensive than necessary

Open treeowl opened this issue 4 years ago • 0 comments

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.

treeowl avatar Dec 27 '20 21:12 treeowl