Multithreading in Python

Multithreading defined as the ability of a processor to execute multiple threads by rapidly switching the control of the CPU between threads concurrently.

Program Multithreading

Program

import _thread
import time
# Define a function for the thread.
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print("%s: %s" %(threadName, time.ctime(time.time())))
# Create two threads as follows.
try:
   _thread.start_new_thread( print_time,("Thread-1", 2,))
   _thread.start_new_thread( print_time,("Thread-2", 4,))
except:
   print("Error: unable to start thread")
while 1:
   pass
Output
Thread-1: Sun Oct 8 01:21:37 2023
Thread-1: Sun Oct 8 01:21:39 2023Thread-2: Sun Oct 8 01:21:39 2023

Thread-1: Sun Oct 8 01:21:41 2023
Thread-2: Sun Oct 8 01:21:43 2023
Thread-1: Sun Oct 8 01:21:43 2023
Thread-1: Sun Oct 8 01:21:45 2023
Thread-2: Sun Oct 8 01:21:47 2023
Thread-2: Sun Oct 8 01:21:51 2023
Thread-2: Sun Oct 8 01:21:55 2023

Program Threading

Program

import threading
def worker(num):
    #thread worker function
    print("Worker: %s", num)
    return
threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()
Output
Worker: %s 0
Worker: %s 1
Worker: %s 2
Worker: %s 3
Worker: %s 4

Program Working with Multithreading

Program

import threading
import time
def worker():
    print(threading.currentThread().getName(), "Starting")
    time.sleep(2)
    print(threading.currentThread().getName(), "Exiting")
def my_service():
    print(threading.currentThread().getName(), "Starting")
    time.sleep(3)
    print(threading.currentThread().getName(), "Exiting")
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start()
Output
worker Starting
Thread-1 (worker) Starting
my_service Starting
worker Exiting
Thread-1 (worker) Exiting
my_service Exiting

Program Working with Multithreading
Program

import threading
TOTAL = 0
class CountThread(threading.Thread):
    def run(self):
        global TOTAL
        for i in range(100):
            TOTAL = TOTAL + 1
        print(TOTAL)
a = CountThread()
b = CountThread()
a.start()
b.start()
Output
100
200