Trouble running multiple infinite loops (GTK + X11 + Signal listener) in parallel in Crystal

Execution contexts could help. Each blocking loop should run in a separate instance of ExecutionContext::Isolated.

However, there’s also a good chance that some of the code you’re using is just not multi-threading safe. That applies to parts of stdlib, as well as many 3rd party shards.
See Charting the route to multi-threading support for some details on how potential thread-safety issues.

You could try to reduce the code that runs in the blocking loops to a minimum. They can just trigger a notification - for example by sending to a channel - while the actual handler runs in the single-threaded main context - at the receiving end of the channel. That should avoid many thread-safety concerns because most of the code runs in a single thread.

2 Likes