Understanding Python Multithreading

Hello,

I am a newbie to python and I am unable to get an idea about threading. Could someone please explain threading and multithreading in python with the help of a simple example?

Multithreading helps you with the execution of multiple tasks at the same time. Python multithreading facilitates sharing of data space and resources of multiple threads with the main thread. This allows efficient and easy communication between the threads.

Multithreading in Python should be used only when there is no existing inter-dependency between the threads. The syntax to create a new thread is as follows –

Using the Threading Module

from threading import *
def MyThread1():
    print("I am in thread1.", "Current Thread in Execution is", current_thread().getName())
def MyThread2():
    print("I am in thread2.", "Current Thread in Execution is", current_thread().getName())
t1 = Thread(target=MyThread1, args=[])
t2 = Thread(target=MyThread2, args=[])
t1.start()
t2.start()

Output

I am in thread1. Current Thread in Execution is Thread-1
I am in thread2. Current Thread in Execution is Thread-2

Using the Thread Module

import _thread
def MyThread1():
    print("This is thread1")
def MyThread2():
    print("This is thread2")
 
_thread.start_new_thread(MyThread1, ())
_thread.start_new_thread(MyThread2, ())

Output

This is thread1
This is thread2

The output of the above code snippet can be different for different runs. This happens because multithreading in Python using the _thread module is unstable.

Example taken from - Scaler Topics