Queue Alternative to Control ruby child Thread

Viewed 71

I'm maintaining a ruby script that contains several instances of same class with a 'scanning thread' (infinite loop scanning some external FTDI/SWD/JLink on externa HW). Threads are created via scanThread_start() and kill via a scanThread_stop() (both are instance method).

As it deals with child process that control external HW part, there is a mechanism to wait and clean everything before exiting the thread. scanThread_stop() sends a :scanStop message via a Queue (one per instance) then wait a class variable (protected by Mutex) to be set to 'inactive' by the scanning Thread. Then it kill the Thread.

It works fine, but as I need to stop/restart scanning devices, the implementation create/destroy threads regularly.

Question 1: As we deal here with only ~ 30 Threads that need to be stop and start only once per minute, is there some benefit to implement a pause/resume mechanism and keep the same Thread alive?


I have implemented methods scanThread_pause() and scanThread_resume() to control Thread x via Queue q.

  • scanThread_resume() just send a message :scanStart to the Thread x.
  • scanThread_pause() performs like scanThread_stop(), but do not kill the Thread so it can be resume later on.

It still work fine, but maybe I can also remove the class variable to check only if q.empty? as I know that Thread x read the queue only in 'safe place' and stop Immediately.

I did some research to improve implementation with various Thread control strategy (Queue, Raise from main Thread...) and didn't find something that fit my need. For example using Raise on Thread may interrupt some child process and so disrupt external HW behavior.

I suppose that there is simple a way to send some message to the Thread and wait response.

In fact this looks like a bidirectional Queue but I did not find any useful link about such kind of object. I can use a pair of Queue (rx/tx) or I Can use IO pipe but i'm sure there is a simple way to do this. Another way might be to use Raise which is pretty simple, but I need to make some part of code in the Thread uninterruptible and I don't know how to.

Question2: What is the best/simple approach to manage control over this scanning Thread?

Thanks in advance for your feedback

0 Answers
Related