Python Multi Threading

I am by no means a Python expert and when researching how to get my own multi threading working I see there are several ways depending on the task that you are performing.
To summarise what I had read over and over, multi processing, spawns multiple processes for your CPU and is best for CPU bound tasks. Multi threading is for I/O bound tasks where there is a lot of waiting.

There seems to be more than these two basic statements to it, I understand that multi processing can have a thread pool. However I’m only dealing with something basic for a lab here.

What I needed was two specific points;

  • The first was to have only have a set amount of threads running at once. I’ll get onto why later.
  • The second was to have the values returned when each thread was executed.

First point, a set amount of threads. I needed this as the base multi threading I have used before has spawned as many threads as devices and then opened up SSH connections to them. While this is ok in a lab environment. If I have 100 devices, then I’m spawning 100 threads. I want to have a little more control.

Second point, in my TACACS script I’m getting output from the devices which is written to a file and used later in the script. Not being able to return a value means I could only login to the device quicker than the standard linear method. But no use to me.

This first multi threads script I am painting walls, two at a time. The output is the thread number (always 0 and 1), and the wall painted. Nothing is returned. Once the print statement telling me which wall is being painted has been output, that’s it.
This takes care of my first requirement

The next version of this is to have an output in a list so we can pick up later. For this I am passing in a list called return_list.
This takes care of the second point.

Further Examples

Leave a Comment

Your email address will not be published. Required fields are marked *