Starting a thread

First things first, let's start a thread:

# start.py
import threading

def sum_and_product(a, b):
s, p = a + b, a * b
print(f'{a}+{b}={s}, {a}*{b}={p}')

t = threading.Thread(
target=sum_and_product, name='SumProd', args=(3, 7)
)
t.start()

After importing threading, we define a function: sum_and_product. This function calculates the sum and the product of two numbers, and prints the results. The interesting bit is after the function. We instantiate t from threading.Thread. This is our thread. We passed the name of the function that will be run as the thread body, we gave it a name, and passed the arguments 3 and 7, which will be fed into the function as a and b, respectively.

After having created the thread, we start it with the homonymous method.

At this point, Python will start executing the function in a new thread, and when that operation is done, the whole program will be done as well, and exit. Let's run it:

$ python start.py
3+7=10, 3*7=21

Starting a thread is therefore quite simple. Let's see a more interesting example where we display more information:

# start_with_info.py
import threading
from time import sleep

def sum_and_product(a, b):
sleep(.2)
print_current()
s, p = a + b, a * b
print(f'{a}+{b}={s}, {a}*{b}={p}')

def status(t):
if t.is_alive():
print(f'Thread {t.name} is alive.')
else:
print(f'Thread {t.name} has terminated.')

def print_current():
print('The current thread is {}.'.format(
threading.current_thread()
))
print('Threads: {}'.format(list(threading.enumerate())))

print_current()
t = threading.Thread(
target=sum_and_product, name='SumPro', args=(3, 7)
)
t.start()
status(t)
t.join()
status(t)

In this example, the thread logic is exactly the same as in the previous one, so you don't need to sweat on it and can concentrate on the (insane!) amount of logging information I added. We use two functions to display information: status and print_current. The first one takes a thread in input and displays its name and whether or not it's alive by calling its is_alive method. The second one prints the current thread, and then enumerates all the threads in the process. This information comes from threading.current_thread and threading.enumerate.

There is a reason why I put .2 seconds of sleeping time within the function. When the thread starts, its first instruction is to sleep for a moment. The sneaky scheduler will catch that, and switch execution back to the main thread. You can verify this by the fact that in the output, you will see the result of status(t) before that of print_current from within the thread. This means that that call happens while the thread is sleeping.

Finally, notice I called t.join() at the end. That instructs Python to block until the thread has completed. The reason for that is because I want the last call to status(t) to tell us that the thread is gone. Let's peek at the output (slightly rearranged for readability):

$ python start_with_info.py
The current thread is
<_MainThread(MainThread, started 140735733822336)>.
Threads: [<_MainThread(MainThread, started 140735733822336)>]
Thread SumProd is alive.
The current thread is <Thread(SumProd, started 123145375604736)>.
Threads: [
<_MainThread(MainThread, started 140735733822336)>,
<Thread(SumProd, started 123145375604736)>
]
3+7=10, 3*7=21
Thread SumProd has terminated.

As you can see, at first the current thread is the main thread. The enumeration shows only one thread. Then we create and start SumProd. We print its status and we learn it is alive. Then, and this time from within SumProd, we display information about the current thread again. Of course, now the current thread is SumProd, and we can see that enumerating all threads returns both of them. After the result is printed, we verify, with one last call to status, that the thread has terminated, as predicted. Should you get different results (apart from the IDs of the threads, of course), try increasing the sleeping time and see whether anything changes.

..................Content has been hidden....................

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