Reading SDL events (via TSDL)

Hello!

I’m trying to read input events from @dbuenzli’s TSDL library in my Lwt application.

API: http://erratique.ch/software/tsdl/doc/Tsdl.Sdl.html#events

val wait_event : event option -> unit result

If I use wait_event I block the OS thread, meaning everything grinds to a halt.

val wait_event_timeout : event option -> int -> bool

This is slightly better, since it allows me to schedule some Lwt threads every now and then, but still halts the main thread.


I feel like I need another OS thread here, and somehow have that write into a Lwt_mvar.t or similar that I can use from inside Lwt.

Can anyone point me to an example of similar code, or to a possible solution for this problem?

1 Like

You may want to check useri. I’m no longer sure if it fully solved the problem in the way you want but it was designed to work both with cooperative concurency and event callbacks (e.g. the browser via jsoo), see here for an example.

3 Likes

Thank you!

I had not considered doing tick-based reading, but that will definitely work for my case.
The alternative quickly becomes unnecessarily complex, so I will adopt your approach. :slight_smile:

By the way: I found this to be a good source of examples of reading various types of input: https://github.com/dbuenzli/useri/blob/master/src-tsdl/useri_backend_tsdl.ml

1 Like

Is it possible to wait for an event in a separate preemptive lwt thread?

You have to be careful with these things, as the underlying OS libraries may have strong requirements about which thread is allowed to get user events (IIRC on macos this had to be done on the main thread). As far as SDL is concerned you have to do this in the same thread that initialized the video subsystem.

3 Likes

Here’s the code I ended up with for this tick-based thing instead of getting into the misty swamps of portable thread synchronization:

1 Like

To add my 0.02 cents to this old thread.

I had a Tsdl + Lwt application that worked fine when I was using software renderers, but then I swapped an Nvidia GPU into the computer and the application stopped updating the window altogether.

Although the SDL docs say you need to make sure you limit stuff like SDL_WaitEvent to the thread that initialized SDL video, the underlying Nvidia library appears to further require (without logging anything?) that this thread is the first application thread. I had tried to coordinate all SDL stuff through a detached thread, which didn’t work.

The solution was to do all of the SDL stuff in my main thread and adopt the polling approach mentioned here to get multi-threading to work. Thanks for posting this!

3 Likes