The idea is that the input will be provided by the console, and will be identified with a unique ‘id’ as the first word of the input. A new thread is spawned when a new id is encountered, with the subsequent input being ‘start’. The thread should close when an input with the same id will say ‘close’. The ordering of the statements is random.
Share
The trick here is to have a single thread (most easily the main thread) do all the reading. That thread will parse the command, start or stop threads, and dispatch commands to the threads. Each thread will have its own Queue from which it reads commands and into which the main thread puts the commands. Let’s see how it might be done.
We’ll start with a little module for the control commands, so that they’re DRY:
Now let’s see the “main”:
There’s nothing much going on here. We make a console, and tell it to read commands and dispatch them to the workers. The console does not return from that until it has run out of input. The call to
@workers.joinmake sure all the workers have finished working and properly shut down before the program exits.Here’s the Console class:
read_and_dispatchis the main loop. All that it is responsible for is reading and parsing input. As long as there is input, it splits it into the worker name and command, and then tells the workers to handle the command.Here’s the Workers class:
This is where most of the meat is. This class creates workers (threads), stop them, and dispatches commands to them. Note that there is no error handling here: If you try to stop a thread that isn’t started, start one that’s already started, or dispatch a command to one that doesn’t exist, the program will crash or misbehave. I’ll leave the handling of those situations as an “exercise for the reader.”
Here’s the Worker class:
This class contains the thread, and the queue used to communicate the between the main thread (the one reading the console) and the worker thread. That queue is also used to stop a thread, synchronously, by putting a STOP_COMMAND in the queue which the thread responds to by exiting. It is best, when you can afford to, to stop threads synchronously rather than asynchronously.
Here’s a simple input file:
And the output when the program is presented with that input: