Multithreading In Python


What is Multithreading in Python and How to Achieve it? Edureka
Multithreading  In Python

Welcome  friends, Today Iam going to explain about Multithreading, This tutorial will give you all the details  about multitheading because it is used in our daily life projects it is important.

So let’s start our tutorial, without any delay :-

In this Multithreading tutorial, we will see different methods to create threads.In this tutorial each section of this post uses many examples and the sample code to explain the concept step by step.

Multithreading is a core concept of software programming that almost all the high-level programming languages support. Hence, the first things you should know are :-

  • What is a thread in python ?
  • What does multithreading and why it is used ?

Multithreading in Python
 Multithreading in Python | Set 1 - GeeksforGeeks
Contents

  • What is a Thread ?
  • What is multithreading ?
  • Advantages of Multithreading
  • Disadvantages of Multithreading
  • Python Multithreading Modules
  • How to use the thread module to create threads?
  • => Example
  • How to use the threading module to create threads?
  • => Steps to implement threads using the threading module
  • => Example
  • => Synchronization

What is a Thread ?
 Multithreading in Python | Set 1 - GeeksforGeeks
A thread is the smallest unit of execution with the independent set of instructions. It is a part of the process and operates in the same context sharing program’s runnable resources like memory. A thread has a starting point, an execution sequence, and a result. It has an instruction pointer that holds the current state of the thread and controls what executes next in what order.

What is multithreading ?
 Python threads synchronization: Locks, RLocks, Semaphores ...
The ability of a process to execute multiple threads parallelly is called multithreading. Multithreading can significantly improve the performance of any program.

Advantages of Multithreading

1.      Multithreading can significantly improve the speed of computation on multiprocessor or multi-core systems because each processor or core handles a separate thread concurrently.

2.      Multithreading allows a program to remain responsive while one thread waits for input, and another runs a GUI at the same time. This statement holds true for both multiprocessor or single processor systems.

3.      All the threads of a process have access to its global variables. If a global variable changes in one thread, it is visible to other threads as well. A thread can also have its own local variables.

Disadvantages of Multithreading

1.      On a single processor system, multithreading would not hit the speed of computation. The performance may downgrade due to the overhead of managing threads.

2.      Synchronization is needed to prevent mutual exclusion while accessing shared resources. It directly leads to more memory and CPU utilization.

3.      Multithreading increases the complexity of the program, thus also making it difficult to debug.

4.      It raises the possibility of deadlocks.

5.      It may cause starvation when a thread does not get regular access to shared resources. The application would then fail to resume its work.

Python Multithreading Modules

Python offers two modules to implement threads in programs.

The principal difference between the two modules is that the module thread implements a thread as a function and n the other side the module  offers an object-oriented approach to enable thread creation.

How to use the thread module to create threads?

 Python Multithreading Tutorial: Concurrency and Parallelism | Toptal

If you decide the  module to apply in your program, then use the following method to create threads :-

Syntax

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

This method is very easy and understandable for creating threads. You can use it to run programs in both Linux and Windows.

This method starts a new thread and returns its identifier. It will invoke the function specified as the “function” parameter with the passed list of arguments. When the  returns, the thread would silently exit.

Here, args is a tuple of arguments.use an empty tuple to call  without any arguments.


Example
 Multithreading in Python for Finance - Towards Data Science
from _thread import start_new_thread
from time import sleep

thread = 1
wait= 2

def factorial(n):
global thread
x = 0

if n < 1:  
print("{}: {}".format('\nThread', thread ))
thread += 1
x= 1
else:
return num = n * factorial( n - 1 )
print("{} != {}".format(str(n), str(return num)))
x = return num

return x

start_new_thread(factorial, (10, ))
start_new_thread(factorial, (9, ))

print("Wait till the threads will not return...")
sleep(wait)

You guys, use your IDE like Pycharm, visual studio code etc to execute python program. Once you execute this program, Output will be shown there.

How to use the threading module to create threads?

 Python GIL global lock - Programmer Sought

The  module combines all the methods of the  module and uses some more features here :-

·         threading.activeCount(): It finds the total number of active thread objects.
·         threading.currentThread(): You can use it to determine the number of thread objects in the caller’s thread control.
·         threading.enumerate(): It will give you a complete list of thread objects that are currently active.

The  class publishes the following methods :-

  • run():             It is the entry point function for any thread.
  • start():             The start() method triggers a thread when the run method gets called.
  • join([time]):     The join() method enables a program to wait for threads to terminate.
  • isAlive():          The isAlive() method verifies an active thread.
  • getName():      The getName() method retrieves the name of a thread.
  • setName():      The setName() method updates the name of a thread.

Example

 Python Multithreading | Mindbowser

import threading
import datetime

class Thread (threading.Thread):
def __init__(self, name, count):
threading.Thread.__init__(self)
self.ID = count
self.name = name
self.count = count
def execute(self):
print("\nStarting " + self.name)
print_date(self.name, self.count)
print("Exiting  before" + self.name)

def date(thr_date, count):
datefield = []
today = datetime.date.today()
datefield.append(today)
print("{}[{}]: {}".format( thr_date, count, datefield[0] ))


thread1 = Thread("Thread", 1)
thread2 = Thread("Thread", 2)


thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("\nExiting the Program before !!!")

Synchronization

The  module has built-in functionality to implement locking that allows you to synchronize threads. Locking is required to control access to shared resources to prevent corruption or missed data.

You can call Lock() method to apply locks, it returns the new lock object. Then, you can invoke the acquire(blocking) method of the lock object to enforce threads to run synchronously.

The optional blocking parameter specifies whether the thread waits to acquire the lock :-

·         Case blocking = 0: The thread would return immediately with a zero value if it fails to acquire the lock and with a one if the lock was successful.
·         Case blocking = 1: The thread blocks and wait for the lock to be released.

The release() method of the lock object is used to release the lock when it is no longer required.

Python’s built-in data structures such as lists, dictionaries are thread-safe as a side-effect of having atomic byte-codes for manipulating them. Other data structures implemented in Python or basic types like integers and floats, don’t have that protection. To guard against simultaneous access to an object, we use a Lock object.

Conclusion

 Multiprocessing vs. Threading in Python: What Every Data Scientist ...

We wish that you would like my tutorial on Multithreading in Python very interesting . The explanations we will given here would surely help in lifting your Python skills.

This is the the end of our tutorial guys.

If you liked this post, then please distribute it among your friend circle or on the social media platforms you use.

Thank you Guys and Good Bye...

Keep learning,


Reactions

Post a Comment

0 Comments