sdl2 icon indicating copy to clipboard operation
sdl2 copied to clipboard

Error when trying to use timers

Open Taneb opened this issue 3 years ago • 4 comments

I'm trying to implement something using SDL timers, but I was getting a segfault whenever the timer first triggered. I've got this down to a fairly small failing example:

import Control.Monad (forever)
import qualified SDL

main :: IO ()
main = do
  SDL.initialize [SDL.InitTimer]
  ticker <- SDL.addTimer 1000 $ \d -> putStrLn "tick" >> return (SDL.Reschedule d)
  forever $ pure ()

This fails with

sdl-experiment: schedule: re-entered unsafely.
   Perhaps a 'foreign import unsafe' should be 'safe'?

This also occurs if I try to use the raw API, but does not occur if I try to port this to C.

Note that in my original larger example, I only got Segmentation fault (core dumped) as the error message, so there might be more than one thing going on here.

GHC 8.10.7, sdl2 Haskell library version 2.5.3.0, SDL2 C library 2.0.14, NixOS

Taneb avatar Dec 20 '21 10:12 Taneb

Oops, that's no good! Would you be able to try GHC's suggestion of changing the FFI imports to be safe? I imagine something addTimer uses is causes this re-entrance

ocharles avatar Dec 20 '21 10:12 ocharles

I can't find anything called schedule. Explicitly marking safe all the FFI calls that addTimer seems to use (addTimerFFI, removeTimerFFI, mkTimerCallback) doesn't seem to help at all.

Taneb avatar Dec 20 '21 11:12 Taneb

Hmmm, possibly initialize itself then? Other than that, it can only imagine it's how we create the callback, but I'll have to get into the code to understand that

ocharles avatar Dec 20 '21 12:12 ocharles

I'm not sure why this fixes it, but having the timer write to an MVar seems to fix the issue!

Taneb avatar Dec 26 '21 08:12 Taneb