Sunteți pe pagina 1din 7

What is multitasking in Python?

What is a thread?
What is multithreading in python?
When to use multithreading in Python?
How to achieve Multithreading in Python?
How to create threads in Python?

 without creating a class


 by extending thread class
 without extending thread class

Advantages of using multithreading in Python

To begin with, let us first try to understand multitasking before we start learning about
Multithreading in Python.

What is Multitasking in Python?


Multitasking, in general, is the capability of performing multiple tasks simultaneously. In
technical terms, multitasking refers to the ability of an operating system to perform
different tasks at the same time. For instance, you are downloading something on your
PC as well as listening to songs and concurrently playing a game, etc. All these tasks
are performed by the same OS an in sync. This is nothing but multitasking which not
just helps you save time but also increases productivity.

There are two types of multitasking in an OS:

 Process-based
 Thread-based

In this article, you will be learning about Thread-based multitasking or Multithreading.

What is a thread?
A thread is basically an independent flow of execution. A single process can consist of
multiple threads. Each thread in a program performs a particular task. For
Example, when you are playing a game say FIFA on your PC, the game as a whole is a
single process, but it consists of several threads responsible for playing the music,
taking input from the user, running the opponent synchronously, etc. All these are
separate threads responsible for carrying out these different tasks in the same program.

Every process has one thread that is always running. This is the main thread. This main
thread actually creates the child thread objects. The child thread is also initiated by the
main thread. I will show you all further in this article how to check the current running
thread.

So with this, I hope you have clearly understood what is a thread. Moving on, let’s see
what is Multithreading in Python.

When to use Multithreading in Python?

Multithreading is very useful for saving time and improving performance, but it cannot
be applied everywhere.
In the previous FIFA example, the music thread is independent of the thread that takes
your input and the thread that takes your input is independent of the thread that runs
your opponent. These threads run independently because they are not inter-dependent.

Therefore, multithreading can be used only when the dependency between individual
threads does not exist.

This article further shows how you can achieve Multithreading in Python.

How to achieve Multithreading in Python?


Multithreading in Python can be achieved by importing the threading module.
Before importing this module, you will have to install this it. To install this on your
anaconda environment, execute the following command on your anaconda prompt:

conda install -c conda-forge tbb

After its successfully installed, you can use any of the following commands to import the
threading module:

1 import threading
2 from threading import *
Now that you have threading module installed, let us move ahead and do Multithreading
in Python.

How to create threads in Python?

Threads in Python can be created in three ways:

1. Without creating a class


2. By extending Thread class
3. Without extending Thread class

Without creating a class

Multithreading in Python can be accomplished without creating a class as well. Here is


an example to demonstrate the same:

Example:

1
from threading import *
2 print(current_thread().getName())
3 def mt():
4 print("Child Thread")
5 child=Thread(target=mt)
child.start()
6 print("Executing thread name :",current_thread().getName())
7

Output:

MainThread
Child Thread
Executing thread name : MainThread
The above output shows that the first thread that is present is, the main thread. This
main thread then creates a child thread that is executing the function and then the final
print statement is executed again by the main thread.

Now let us move ahead and see how to do Multithreading in python by extending the
Thread class.

By extending the Thread class:

When a child class is created by extending the Thread class, the child class represents
that a new thread is executing some task. When extending the Thread class, the child
class can override only two methods i.e. the __init__() method and the run() method. No
other method can be overridden other than these two methods.

Here is an example of how to extend the Thread class to create a thread:

Example:

1
2 import threading
import time
3 class mythread(threading.Thread):
4 def run(self):
5 for x in range(7):
6 print("Hi from child")
7 a = mythread()
a.start()
8 a.join()
9 print("Bye from",current_thread().getName())
10
Output:
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Hi from child
Bye from MainThread

The above example shows that class myclass is inheriting the Thread class and the
child class i.e myclass is overriding the run method. By default, the first parameter of
any class function needs to be self which is the pointer to the current object. The output
shows that the child thread executes the run() method and the main thread waits for the
childs execution to complete. This is because of the join() function, which makes the
main thread wait for the child to finish.
This method of creating threads is the most preferred method because its the standard
method. But in case you want to create threads without inheriting or extending the
Thread class, you can do it in the following manner.

Without Extending Thread class

To create a thread without extending the Thread class, you can do as follows:
Example:

1
2 from threading import *
class ex:
3 def myfunc(self): #self necessary as first parameter in a class func
4 for x in range(7):
5 print("Child")
6 myobj=ex()
7 thread1=Thread(target=myobj.myfunc)
thread1.start()
8 thread1.join()
9 print("done")
10
Output:

Child
Child
Child
Child
Child
Child
Child
done

The child thread executes myfunc after which the main thread executes the last print
statement.

Advantages of using threading


Multithreading has many advantages some of which are as follows:

 Better utilization of resources


 Simplifies the code
 Allows concurrent and parallel occurrence of various tasks
 Reduces the time consumption or response time, thereby, increasing the
performance.
Here is an example to check how long it takes for a code to execute with and without
multithreading in python:

Example:
1
2 import time
3 def sqr(n):
4 for x in n:
time.sleep(1)
5
x%2
6 def cube(n):
7 for x in n:
8 time.sleep(1)
9 x%3
n=[1,2,3,4,5,6,7,8]
10 s=time.time()
11 sqr(n)
12 cube(n)
13 e=time.time()
14 print(e-s)
15
Output:

16.042309284210205

The above is the output time taken to execute the program without using threads. Now
let us use threads and see what happens to the same program:

Example:

1 import threading
from threading import *
2
import time
3 def sqr(n):
4 for x in n:
5 time.sleep(1)
6 print('Remainder after dividing by 2',x%2)
def cube(n):
7 for x in n:
8 time.sleep(1)
9 print('Remainder after dividing by 3',x%3)
10 n=[1,2,3,4,5,6,7,8]
11 start=time.time()
t1=Thread(target=sqr,args=(n,))
12 t2=Thread(target=cube,args=(n,))
13 t1.start()
14 time.sleep(1)
15 t2.start()
t1.join()
16 t2.join()
17 end=time.time()
18 print(end-start)
19
20
21
22
Output: 9.040220737457275
The above output clearly shows that the time taken when we use threads is much less
compared to the time taken for the same program to execute without using threads.

I hope you are clear with the concepts covered under this article related to
Multithreading in Python. Make sure to practice as much as possible as this is one of
the most important concepts used in programming.

S-ar putea să vă placă și