Multitasking with threads

A thread is a lightweight process that shares the same address and memory space as its parent process. It runs in parallel on the processor cores, thereby giving us parallelism and multitasking capabilities. The fact that it shares the same address and memory space as that of the parent process makes the whole operation of multitasking very lightweight, because there is no context switching overhead involved. In context switching, when a new process is scheduled to be executed, the operating system needs to save the state of the previous process, including the process ID, the instruction pointer, the return address, and so on.

This is a time-consuming activity. Since multitasking with threads doesn't involve the creation of new processes to achieve parallelism, threads provide a very good performance in multitasking activities. Just as in Java we have the Thread class or the runnable interface to implement threads, in Python we can do this using the Thread module to implement threads. There are typically two ways to implement threads in Python: one in Java style and one that is more Pythonic. Let's take a look at both.

The following code shows the Java-like implementation, where we subclass the threading class and override the run() method. We place the logic or task that we wish to run in parallel with the threads inside the run() method:

import threading
>>> class a(threading.Thread):
... def __init__(self):
... threading.Thread.__init__(self)
... def run(self):
... print("Thread started")
...
>>> obj=a()
>>> obj.start()
Thread started

Here, we have got a method (run()), which, in this case, is made to execute in parallel. This is what Python explores with its other method of threading, in which we can make any method execute in parallel with the help of threads. We can use any method of our choice and that method can take any arguments.

The following code snippet shows the other way of using threading. Here, we can see that we defined an add(num1,num2) method normally and then used it with threads:

>>> import threading
>>> def add(num1,num2):
... print(num1 + num2)
...
>>> for i in range(5):
... t=threading.Thread(target=add,args=(i,i+1))
... t.start()
...
1
3
5
7
9

The for loop creates a thread object t. On calling the start() method, the method specified in the target parameter while creating the thread object is invoked. In the preceding case, we have passed the add() method to the thread instance. The arguments that are to be passed to the method to be invoked with threads are passed under the args parameter as a tuple. The add() method is called five times via threads and the output is printed on the screen, as shown in the preceding example.

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

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