Let us consider the block of code below. The threading module and time module would be used for the following example.
One function, odd_print(), has been defined to print a number ‘1’, pause for one second, and print the next odd number. This for loop would be repeated five times.

Two threads are then started by calling the same odd_print() function. Note that this time, the lines of code starting the threads (Line 11 to 19) are not nestled within the if __name__ == ‘__main__’: command. (See Threading blog post) The code would still run, just that it is not considered as a separate application.
The result is then obtained below, where each of the threads print out the odd numbers sequence half a second apart.

There is a function within the threading module where a thread could be locked, such that it needs to complete executing before the second (or subsequent) thread is being executed. This is achieved by defining the lock variable as the function in Line 4, followed by Line 8 to lock the thread, and with the lock being released after the for loop in Line 13.
By default, all threads are not locked when called.

If you also realised, in Line 15 and 16, the args = () is missing. It has been left out from the code as no particular argument is being parsed into the odd-print() function, and is thus redundant.
With the lock in place, the first thread will execute by printing the five odd numbers, followed by the second thread printing the same set of odd numbers.

Alternatively, a Timer function within the threading module could be utilised. In the code shown below, Line 12 utilises the Timer function to call the function odd_print after ten seconds as a second thread. Since the first thread takes about five second to complete printing the five odd numbers, there is ample time before the second thread is called after the first thread had completed printing the numbers, achieving the same printout result.

Although threads are being executed separately, they are still considered as part of the same code. Any issues or errors with a thread may affect the other threads. Is it possible then to really segregate two blocks of code within the same programme? We’ll explore that in the next post.
Is there any way to make the above codes more concise and elegant? Feel free to comment.
One thought on “Threading. Part II – Locks & Timer”