Suppose we have the following code consisting of two functions. Line 3 to 8 defines the odd_print function where it uses a for loop to iterate five times, by first printing the number ‘1’ (Line 6), pauses for one second (Line 7), and adds two to the previous number giving us the next odd number. Line 10 to 15 defines the even_print function, doing pretty much the same thing. What happens when the two functions are being called sequentially in Line 17 and 18?

And as expected, these two functions are executed in a sequential manner, printing a series of five odd numbers, followed by a series of five even numbers.

Thus, whenever the functions in Python are called one after another, the first function (or block of code) would be executed first, before the next function (or block of code) would be executed. For the purpose of this illustration, a one second pause is introduced before the next number is printed. During this pause, the programme essentially waits for the one second to lapse before executing the next line of code.
Is there a way to make use of this “waiting” time to ask the programme to execute another block of code? The answer to this could be found using the threading module. These two functions are then executed in a parallel manner.

Line 18 to 28 execute the two functions that were defined earlier in a parallel manner called threads.
Line 18 is not actually needed in this case; Line 20 to 28 need not be nestled under this if conditional, but we’ll cover this line of code separately in a later blog post.
Line 20 and 21 creates the “parallel” threads, one for each of the functions.
Line 23 starts the execution of the first thread consisting of the odd_print function.
Line 24 introduces a slight pause of half a second in the code as it helps to prevent the two threads from mixing up.
Line 25 starts the execution of the second thread consisting of the even_print function.
Line 27 and 28 waits for the respective threads to complete before ending the application.
Thus, during the one second pause after printing the number ‘1’ from odd_print function, half of which is spent waiting prior the start of the next thread printing out number ‘2’ from the other even_print function. As a result, we have the two threads being executed in parallel giving the result as follows:

Is there any way to make the above codes more concise and elegant? Feel free to comment.
2 thoughts on “Threading.”