Because Rust does not have have the built-in ability to read from a file in a non-blocking manner, I have to spawn a thread which reads the file /dev/input/fs0
in order to get joystick events. Suppose the joystick is unused (nothing to read), so the reading thread is blocked while reading from the file.
Is there a way for the main thread to force the blocking read of the reading thread to resume, so the reading thread may exit cleanly?
In other languages, I would simply close the file in the main thread. This would force the blocking read to resume. But I have not found a way to do so in Rust, because reading requires a mutable reference to the file.
The idea is to call
File::read
only when there is available data. If there is no available data, we check a flag to see if the main thread requested to stop. If not, wait an try again.Here is an example using nonblock crate:
Here is an example using
poll
binding of nix crate. The functionpool
waits (with timeout) for specific events: