I'm doing some joystick programming in Ruby on Linux using a Ruby extension which wraps the basic functionality of joystick.h. Getting a joystick event is a blocking read by default, but I don't want that to interrupt the game loop.
Currently I'm hacking around it by making non-blocking calls to the joystick and running that in a really fast loop. That works, but it also makes the script use 100% CPU because I want the joystick events as close to real time as possible.
I'm trying to do something like
input = Thread.new do
while e = joystick.event
@event = e
end
end
main = Thread.new do
while true
sleep 0.1
puts @event
end
end
But even then, the joystick.event
call blocks the main thread. Am I totally misunderstanding how Ruby threads work, or how joysticks work on Linux? Or is there a totally different way of approaching this that is better?
I needed to make the read call in the C extension using rb_thread_blocking_region
. Works perfectly now!