Skip to main content

Thread in Python

 
Thread is a collection of light-weight subprocess to execute the program, in the application, we will use Multithreading to implement multitasking.
using Multi-threading we can execute more than one process simultaneously in a single resource.
O/s is the best example of multi-threading because it can execute more than one program simultaneously.
When we want to create a game application then parallel execution is mandatory, which can be managed by the Multi-threading process.
Thread Life Cycle:-
Syntax of threading:-
import threading
class Classname(threading.Thread):
      functionality
      ........

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 ,it will provide memory to store data
t1.start()  #start() is the predefine method which will convert thread process to runnable state to running state
Multithreading:-  If we start more then one Thread object simultaneous then it is called multithreading.
It is used to execute multiple programs set simultaneous.
 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 ,it will provide memory to store data
t1.start()  #start() is the predefine method which will convert thread process to runnable state to running state
t2 = ThreadExample()
t2.start()
t3 = ThreadExample()
t3.start()      
Thread Process Synchronization:-
using this we can provide multi-threading execution is waiting for the state until the current thread process completed. when the process completed then join() will notify another thread and it will be executed .using the join()  method we can synchronize the thread process.
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 ,it will provide memory to store data
t1.start()  #start() is the predefine method which will convert thread process to runnable state to running state
t1.join()
t2 = ThreadExample()
t2.start()
t2.join()
t3 = ThreadExample()
t3.start()
 Example of Thread?
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 = self.s + str(i) + "*"
            self.fact=self.fact*i
            time.sleep(1)
        print("result is "+self.s+" = "+str(self.fact))
t1 = Thread1()
t1.start()
t1.join()
t2 = Thread2()
t2.start()
How to implement Thread for procedural programming?
We can call the method under the thread object using target parameters.
import time
import threading
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()
 Another Example of Thread to calculate table using class-based and method based program:-
Class based 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(str(self.num*i) + " ")
            time.sleep(1)

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

Method Based Program:-

import threading
import time
def table(num):
    for i in range(1,11):
            print(str(num*i) + " ")
            time.sleep(1)
t = threading.Thread(target=table(5))
t.start()
t1 = threading.Thread(target=table(9))
t1.start()

How to implement Thread Synchronization?

In multithreading when multiple threads are working simultaneously on a shared resource like a file(reading and writing data into a file), then to avoid concurrent modification error(multiple threads accessing the same resource leading to inconsistent data) some sort of locking mechanism is used wherein when one thread is accessing a resource it takes a lock on that resource and until it releases that lock no other thread can access the same resource.
Lock Object: Python Multithreading
In the threading module of Python, for efficient multithreading, a primitive lock is used. This lock helps us in the synchronization of two or more threads. Lock class perhaps provides the simplest synchronization primitive in Python.
The primitive lock can have two states: locked or unlocked and is initially created in an unlocked state when we initialize the Lock object. It has two basic methods, acquire() and release().
Following is the basic syntax for creating a Lock object:
import threading
threading.Lock()
Lock objects use two methods, they are:
acquire(blocking=True, timeout=-1) method
This method is used to acquire the lock. When it is invoked without arguments, it blocks until the lock is unlocked.
This method can take 2 optional arguments, they are:
blocking flag which if sent as False will not block the thread if the lock is acquired by some other thread already and will return False as result. If you provide the value for this blocking flag as True then the calling thread will be blocked if some other thread is holding the lock and once the lock is released then your thread will acquire the lock and return True.
the timeout argument is used to provide a positive floating-point value, which specifies the number of seconds for which the calling thread will be blocked if some other thread is holding the lock right now. The default value which is -1 means the thread will be blocked for an indefinite time if it cannot acquire the lock immediately.
release() method
It is used to release an acquired lock. If the lock is locked, this method will reset it to unlocked, and return. Also, this method can be called from any thread.
When this method is called, one out of the already waiting threads to acquire the lock is allowed to hold the lock.
Also, it throws a RuntimeError if it is invoked on an unlocked lock.
Time for an Example!
Below we have a simple python program in which we have a class SharedCounter which will act as the shared resource between our threads.
We have a task method from which we will call the increment() method. As more than one thread will be accessing the same counter and incrementing its value, there are chances of concurrent modification, which could lead to inconsistent value for the counter.
Example to thread synchronization:-
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\n")
        self.lock.acquire()
        try:
            print('Acquired', self.counter,"\n")
            self.counter = self.counter + 1
        finally:
            print('Released a lock, counter value: ', self.counter,"\n")
            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('Waiting for worker threads')
#t1.join()
#t2.join()    
print('Counter:', sCounter.counter)
Thread Assignments:-
1)  Create DICE GAME?
2) CREATE Automated ATM System?

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 a Comment

POST Answer of Questions and ASK to Doubt

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...