swaywm / hsroots

A Haskell wrapper/binding to wlroots
GNU Lesser General Public License v2.1
39 stars 10 forks source link

Listener finalizer gets called early #4

Open georgewsinger opened 5 years ago

georgewsinger commented 5 years ago

addListener finalizers (or more specifically: finalizers associated with their wl_listeners) get called early in hsroots, causing compositors to freeze. Here is a minimum reproducible example:

outputFrameNotify :: WlListener WlrOutput
outputFrameNotify = WlListener $ \ptrWlrOutput ->
  do now <- getTime Realtime
     putStrLn (show now)  --- <-- This pauses after a few seconds due to an early finalizer call

newOutputNotify :: WlListener WlrOutput
newOutputNotify = WlListener $ \ptrWlrOutput ->
  do let outputSignals = getOutputSignals ptrWlrOutput
     let frameSignal  = outSignalFrame outputSignals
     addListener outputFrameNotify frameSignal
     return ()

main :: IO ()
main = do displayServer <- displayCreate
          eventLoop     <- displayGetEventLoop displayServer
          ptrBackend    <- backendAutocreate displayServer

          let newOutputSignal = (backendEvtOutput $ backendGetSignals ptrBackend) :: Ptr (WlSignal WlrOutput)
          addListener newOutputNotify newOutputSignal

          backendStart ptrBackend
          displayRun displayServer
          displayDestroy displayServer
Ongy commented 5 years ago

Well, this is a bug in your appliaction. Or maybe a "documentation bug", since it's probably not clear to anyone but me^^

The way the listeners (and the associated ListenerToken) works is that the token has a cleanup function associated with it, that will run when the runtime decides to free the listener. In your example code that happens instantly, because you never assign the return value to anything, thus it can be freed instantly.

I had originally intended to have this as main way to remove listeners (control their lifetime) but this turned out to not be viable, because major GC runs are rather rare. And those are required to free the token if it ever escaped a local scope (e.g. via IORef or returned in a larger struct that lives for a while).

So in practice you should keep the LIstenerToken around and remove it by hand when it's no longer required.

OTOH I'll keep this as valid complaint and change the behaviour from removing itself on GC to complaining loudly if it hasn't been removed, since that's a bug and the GC shouldn't be relied on here.