# SDL_GameController automatic detection

Here's something that's been bugging me all day: Controller detection in SDL.

First thing is that it doesn't automatically detect when a controller is connected. Finding out when a controller is disconnected is no problem:

if(joystick.closed > 0) { SendEvent(E_CONTROLLER_DISCONNECTED); //cleanup }


I simply have a little loop to detect for new controllers:

SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
joysticks_.Clear();
joysticks_.Resize(SDL_NumJoysticks());


Which works but is very, very slow. Regardless if I have a controller plugged in or not, this step alone takes 10-20ms. Even spacing it apart every few seconds, there are obviously noticable lag spikes whenever I am doing the detection; even with another thread, the lag spikes are still there. However I have not found any better alternative.

This type of behavior is imperitive to proper operation. This is especially so since if a controller gets disconnected, it won't automatically re-open in SDL when I reconnected it. Is there any better way to do this?

Oh, and as another point to make, I don't want to use SDL Events. They do basically what I've listed above, but don't work well with my existing multithreaded approach.

• Only allow controllers to be plugged in while in a menu? – Jari Komppa Apr 14 '14 at 8:29
• Is upgrading to SDL 2.0 an option for you? The new version reportedly supports hot-plugging joysticks. – Michael Kristofik Apr 17 '14 at 13:50
• I'm running 2.0.1 atm. – user39686 Apr 17 '14 at 14:39