Starting a thread with the thread module

In the thread module, new threads are created to execute functions concurrently. As we have mentioned, the way to do this is by using the thread.start_new_thread() function:

thread.start_new_thread(function, args[, kwargs])

When this function is called, a new thread is spawned to execute the function specified by the parameters, and the identifier of the thread is returned when the function finishes its execution. The function parameter is the name of the function to be executed, and the args parameter list (which has to be a list or a tuple) includes the arguments to be passed to the specified function. The optional kwargs argument, on the other hand, includes a separate dictionary of additional keyword arguments. When the thread.start_new_thread() function returns, the thread also terminates silently.

Let's look at an example of using the thread module in a Python program. If you have already downloaded the code for this book from the GitHub page, go ahead and navigate to the Chapter03 folder and the Chapter03/example2.py file. In this example, we will look at the is_prime() function that we have also used in previous chapters:

# Chapter03/example2.py

from math import sqrt

def is_prime(x):
if x < 2:
print('%i is not a prime number.' % x)

elif x == 2:
print('%i is a prime number.' % x)

elif x % 2 == 0:
print('%i is not a prime number.' % x)

else:
limit = int(sqrt(x)) + 1
for i in range(3, limit, 2):
if x % i == 0:
print('%i is not a prime number.' % x)

print('%i is a prime number.' % x)

You may have noticed that there is quite a difference in the way this is_prime(x) function returns the result of its computation; instead of returning true or false, to indicate whether the x parameter is a prime number, this is_prime() function directly prints out that result. As you saw earlier, the thread.start_new_thread() function executes the parameter function through spawning a new thread, but it actually returns the thread's identifier. Printing out the result inside of the is_prime() function is a workaround for accessing the result of that function through the thread module.

In the main part of our program, we will loop through a list of potential candidates for prime numbers, and we will call the thread.start_new_thread() function on the is_prime() function and each number in that list, as follows:

# Chapter03/example2.py

import _thread as thread

my_input = [2, 193, 323, 1327, 433785907]

for x in my_input:
thread.start_new_thread(is_prime, (x, ))

You will notice that, in the Chapter03/example2.py file, there is a line of code to take in the user's input at the end:

a = input('Type something to quit: 
')

For now, let's comment out this last line. Then, when we execute the whole Python program, it will be observed that the program terminates without printing out any output; in other words, the program terminates before the threads can finish executing. This is due to the fact that, when a new thread is spawned through the thread.start_new_thread() function to process a number in our input list, the program continues to loop through the next input number while the newly created thread executes.

So, by the time the Python interpreter reaches the end of the program, if any thread has not finished executing (in our case, it is all of the threads), that thread will be ignored and terminated, and no output will be printed out. However, once in a while, one of the output is 2 is a prime number. which will be printed out before the program terminates, because the thread processing the number 2 is able to finish executing prior to that point.

The last line of code is another workaround for the thread module—this time, to address the preceding problem. This line prevents the program from exiting until the user presses any key on their keyboard, at which time the program will quit. The strategy is to wait for the program to finish executing all of the threads (that is, to finish processing all of the numbers in our input list). Uncomment the last line and execute the file, and your output should be similar to the following:

> python example2.py
Type something to quit:
2 is a prime number.
193 is a prime number.
1327 is a prime number.
323 is not a prime number.
433785907 is a prime number.

As you can see, the Type something to quit: line, which corresponds to the last line of code in our program, was printed out before the output from the is_prime() function; this is consistent with the fact that that line is executed before any of the other threads finish executing, most of the time. I say most of the time because, when the thread that is processing the first input (the number 2) finishes executing before the Python interpreter reaches the last line, the output of the program would be something similar to the following:

> python example2.py
2 is a prime number.
Type something to quit:
193 is a prime number.
323 is not a prime number.
1327 is a prime number.
433785907 is a prime number.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.171.51