Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Thread in Python

Python Multithreading – Complete Guide

Python Multithreading

A Thread is a lightweight subprocess used to execute tasks in parallel. Python supports multithreading, allowing multiple tasks to run simultaneously within the same program.

Operating Systems use multithreading to run multiple applications at the same time. Game development, animations, and real-time systems require multithreading to run parallel executions smoothly.

Thread Life Cycle

Thread Life Cycle

Basic Syntax of Threading

import threading

class Classname(threading.Thread):
    # functionality
    pass

Example: Simple Thread Execution

import threading
import time

class ThreadExample(threading.Thread):
    def run(self):
        for i in range(1, 10):
            print("Process is " + str(i))
            time.sleep(1)

t1 = ThreadExample()  # New state, thread memory allocated
t1.start()            # Moves thread to running state

Multithreading Example

import threading
import time

class ThreadExample(threading.Thread):
    def run(self):
        for i in range(1,10):
            print("Process is " + str(i))
            time.sleep(1)

t1 = ThreadExample()
t1.start()

t2 = ThreadExample()
t2.start()

t3 = ThreadExample()
t3.start()

Thread Synchronization using join()

Thread synchronization ensures that one thread waits until another completes.

import threading
import time

class ThreadExample(threading.Thread):
    def run(self):
        for i in range(1, 10):
            print("Process is " + str(i))
            time.sleep(1)

t1 = ThreadExample()
t1.start()
t1.join()

t2 = ThreadExample()
t2.start()
t2.join()

t3 = ThreadExample()
t3.start()

Example: Thread with Inheritance

import threading
import time

class Thread1(threading.Thread):
    def __init__(self):
        super(Thread1, self).__init__()
        self.num = int(input("Enter number: "))

    def run(self):
        for i in range(1, 11):
            print(self.num * i)
            time.sleep(1)

class Thread2(Thread1):
    def __init__(self):
        super(Thread2, self).__init__()

    def run(self):
        self.s = ''
        self.fact = 1
        for i in range(self.num, 0, -1):
            self.s += str(i) + "*"
            self.fact *= i
            time.sleep(1)
        print("result is " + self.s + " = " + str(self.fact))

t1 = Thread1()
t1.start()
t1.join()

t2 = Thread2()
t2.start()

Threading in Procedural Programming (Using target)

import threading
import time

def fun():
    for i in range(1, 10):
        print(i)
        time.sleep(1)

t1 = threading.Thread(target=fun)
t1.start()
t1.join()

t2 = threading.Thread(target=fun)
t2.start()

Class-Based Thread Example (Table Program)

import threading
import time

class Table(threading.Thread):
    def __init__(self, num):
        super().__init__()
        self.num = num

    def run(self):
        for i in range(1, 11):
            print(self.num * i)
            time.sleep(1)

t = Table(5)
t.start()
t.join()

t1 = Table(9)
t1.start()

Method-Based Thread Example (Table Program)

import threading
import time

def table(num):
    for i in range(1, 11):
        print(num * i)
        time.sleep(1)

t = threading.Thread(target=lambda: table(5))
t.start()

t1 = threading.Thread(target=lambda: table(9))
t1.start()

Thread Synchronization Using Lock()

When multiple threads use the same resource (file, variable), use Lock to avoid data corruption.

Lock Example

import threading
import time
from random import randint

class SharedCounter(object):
    def __init__(self, val=0):
        self.lock = threading.Lock()
        self.counter = val

    def increment(self):
        print("Waiting...")
        self.lock.acquire()
        try:
            print("Acquired", self.counter)
            self.counter += 1
        finally:
            print("Released lock, counter value:", self.counter)
            self.lock.release()

def xyz(c):
    r = randint(1, 5)
    for i in range(r):
        c.increment()
    print("Done")

sCounter = SharedCounter()

t1 = threading.Thread(target=xyz, args=(sCounter,))
t1.start()

t2 = threading.Thread(target=xyz, args=(sCounter,))
t2.start()

print("Counter:", sCounter.counter)

Thread Assignments

  1. Create a Dice Game using multithreading
  2. Create an Automated ATM System with multithreaded operations

Post a Comment

11 Comments

  1. import threading
    import time



    class Table(threading.Thread):

    def accept(self,a):
    self.a = a
    def run(self):
    for i in range(1,11):
    print(self.a, ' * ', i, ' = ',self.a * i)
    time.sleep(1)



    obj =Table()
    obj.accept(int(input("Enter number")))
    obj.start()





    ReplyDelete
  2. #Using Threading table,factorial and prime
    import threading
    import time

    class Table(threading.Thread):

    def accept(self,a):
    self.a = a

    def run(self):
    for i in range(1,11): #Table
    print(self.a, ' * ', i, ' = ',self.a * i)
    time.sleep(.2)

    self.b=self.a
    self.f = 1

    while(self.a>1): #Factorial
    self.f =self.f *self.a
    self.a = self.a-1
    print("Factorial of ",self.b ," is = ",self.f)
    time.sleep(.2)

    self.c=0
    for j in range(2,self.b): #Prime
    if self.b%j==0:
    self.c = self.c+1
    if self.c>0:
    print(self.b," Is Not Prime Number")
    else:
    print(self.b," Is Prime Number")


    obj =Table()
    obj.accept(int(input("Enter number = ")))
    obj.start()

    ReplyDelete
  3. #Using Threading table,factorial and prime
    import threading
    import time
    x =int(input("Enter Number to check Factorial, Prime & Table = "))
    class A(threading.Thread):
    def __init__(self):
    super(A,self).__init__()
    self.a = x

    def run(self):
    for i in range(1,11):
    print(str(self.a) + " * " + str(i)+ " = " + str(self.a*i))
    time.sleep(.2)

    class B(A):
    def __init__(self):
    super(B,self).__init__()
    def run(self):
    f=1
    s=''
    for j in range(self.a,0,-1):
    if j>1:
    s = s + str(j) + " * "
    else:
    s = s + str(j) + " = "
    f = f*j

    print("Factorial of " +str(self.a) + " is "+ " "+str(s) +str(f))
    time.sleep(.2)

    class C(B):
    def __init__(self):
    super(C,self).__init__()
    def run(self):
    c= 0
    for k in range(2,self.a):
    if self.a%k == 0:
    c=c+1
    if c>0:
    print(str(self.a) + " Is Not A Prime Number")
    else:
    print(str(self.a) + " Is A Prime Number")

    t1 =A()
    t1.start()
    t1.join()
    t2 = B()
    t2.start()
    t2.join()
    t3 = C()
    t3.start()

    ReplyDelete
  4. #Dice Game
    import threading
    import time
    import random

    class A(threading.Thread):
    def _init__(self):
    super(A,self).__init__()

    def run(self):
    scr1 = 0
    self.c1 = 0
    f1 = True
    while f1:
    self.p1 = input("Press S to start game and E to end the game = ")
    if self.p1 == 's' :
    x1 = random.randint(1,8)
    print("Number is = " + str(x1))
    scr1 = scr1 + x1
    self.c1 =self.c1 +1
    print("Your score is = " + str(scr1))
    if self.p1 =='e':
    print("Game Over")
    break
    if scr1>=20:
    print("PLAYER 1 TRIED = ",str(self.c1)," TIMES")
    break

    class B(threading.Thread):
    def __init__(self):
    super(B,self).__init__()

    def run(self):
    scr2 = 0
    self.c2 = 0
    f2 =True
    while f2:
    self.p2 = input("Press S to start game and E to end the game = ")
    if self.p2 == 's':
    x2 = random.randint(1,8)
    print("Number is = " +str(x2))
    scr2 = scr2 + x2
    self.c2 =self.c2 +1
    print("Your Score is = " +str(scr2))
    if self.p2 == 'e':
    print("Game Over")
    break
    if scr2>=20:
    print("PLAYER 2 TRIED = ",str(self.c2), " TIMES")
    f2 = False

    t1 =A()
    t1.start()
    t1.join()
    t2 =B()
    t2.start()
    t2.join()

    ReplyDelete
  5. #Create DICE GAME
    # Ankit Saxena

    import random
    while True:
    print(random.randint(1,6))
    roll = input("Want to roll the dice again ? (y/n)")
    if roll.lower()== "y":
    continue
    else:
    break

    ReplyDelete
  6. # Table using threading :-

    import threading
    import time

    class table(threading.Thread):
    def accept(self,n):
    self.n=n
    def run(self):
    for i in range(1,11):
    print(f"{self.n}*{i}={self.n*i}")
    time.sleep(.5)
    obj=table()
    obj.accept(int(input("enter number")))
    obj.start()

    ReplyDelete
  7. import random

    player = random.randint(1,6)
    ai = random.randint(1,6)
    roll=(input("roll the dice Y/N:"))
    if "Y":
    if player > ai :
    print("You win",ai) # notice indentation
    else:
    print("You lose",player)
    else:
    print("thanku for playing this game")

    ReplyDelete
  8. #Table 5 and 6
    import threading
    import time
    class Table(threading.Thread):
    def table(self,num):
    self.num=num
    def run(self):
    for i in range(1,11):
    print(str(self.num*i)+" ")
    time.sleep(1)

    t=Table()
    t.table(5)
    t.start()
    t.join()

    ReplyDelete
  9. # ) Create DICE GAME

    import random
    a=input("enter first")
    n2=random.randrange(1,6)
    print(n2)
    b=input("enter second")
    n3=random.randrange(1,6)
    print(n3)
    c=input(a)
    n4=random.randrange(1,6)
    print(n4)
    d=input(b)
    n6=random.randrange(1,6)
    print(n6)
    e=input(a)
    n7=random.randrange(1,6)
    print(n7)
    f=input(b)
    n9=random.randrange(1,6)
    print(n9)
    j=input(a)
    n8=random.randrange(1,6)
    print(n8)
    g=input(b)
    n12=random.randrange(1,6)
    print(n12)

    print("### Game Over ###")
    T1=n2+n4+n7+n8
    T2=n3+n6+n9+n12
    print("total_first=",T1,"Player 1 rolled"+" "+str(n2)+" "+str(n4)+" "+str(n7)+" "+str(n8))
    print("total_second=",T2,"Player 2 rolled"+" "+str(n3)+" "+str(n6)+" "+str(n9)+" "+str(n12))

    if T1==T2:
    print("first and second dono vin="+str(a)+str(b),T1,T2)
    if T1>T2:
    print("player first vin="+str(a),T1)
    if T1<T2:
    print("player second vin="+str(b),T2)

    ReplyDelete
  10. #Create DICE GAME
    import random
    a=input("enter first")
    n2=random.randrange(1,6)
    print(n2)
    b=input("enter second")
    n3=random.randrange(1,6)
    print(n3)
    c=input(a)
    n4=random.randrange(1,6)
    print(n4)
    d=input(b)
    n6=random.randrange(1,6)
    print(n6)
    e=input(a)
    n7=random.randrange(1,6)
    print(n7)
    f=input(b)
    n9=random.randrange(1,6)
    print(n9)
    j=input(a)
    n8=random.randrange(1,6)
    print(n8)
    g=input(b)
    n12=random.randrange(1,6)
    print(n12)

    print("### Game Over ###")
    T1=n2+n4+n7+n8
    T2=n3+n6+n9+n12
    print("total_first=",T1,"Player 1 rolled"+" "+str(n2)+" "+str(n4)+" "+str(n7)+" "+str(n8))
    print("total_second=",T2,"Player 2 rolled"+" "+str(n3)+" "+str(n6)+" "+str(n9)+" "+str(n12))

    if T1==T2:
    print("first and second dono vin="+str(a)+str(b),T1,T2)
    if T1>T2:
    print("player first vin="+str(a),T1)
    if T1<T2:
    print("player second vin="+str(b),T2)

    ReplyDelete

  11. #CREATE Automated ATM System
    from threading import Thread
    class Atm:
    def __init__(self):
    self.pin=9589
    self.balance=50000

    def menu(self):
    print("""
    Welcome in Banking system
    1. check balance
    2. withdraw
    3. Deposit
    4. Exit
    """)
    option=int(input("Enter your option"))
    if option == 1:
    self.check_balance()
    elif option == 2:
    self.withdraw()
    elif option == 3:
    self.deposit()
    elif option == 4:
    print("Exit")

    def check_balance(self):
    input_pin=int(input("Enter your pin: "))
    if input_pin == self.pin:
    print("Your balance is :",self.balance)
    else:
    print("Your pin is incorrect")

    def withdraw(self):
    input_pin=int(input("Enter your pin: "))
    if input_pin == self.pin:
    input_wbalance=int(input("Enter your withdraw amount"))
    if input_wbalance <=self.balance:
    self.balance=self.balance-input_wbalance
    print("your updated balance is :",self.balance)
    else:
    print("Insufficient balance")
    else:
    print("Your pin is incorrect")

    def deposit(self):
    input_pin=int(input("Enter your pin: "))
    if input_pin == self.pin:
    input_dbalance=int(input("Enter your deposit amount"))
    self.balance=self.balance+input_dbalance
    print("your updated balance is :",self.balance)
    else:
    print("Your pin is incorrect")


    e1=Atm()
    t1=Thread(target=e1.menu())
    t1.start()
    t2=Thread(target=e1.menu())
    t2.start()
    t3=Thread(target=e1.menu())
    t3.start()
    t4=Thread(target=e1.menu())
    t4.start()




    ReplyDelete

POST Answer of Questions and ASK to Doubt