Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

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 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()
        

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 same resource leading to inconsistent data) some sort of locking mechanism is used where in 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.

Primitive lock can have two States: locked or unlocked and is initially created in 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.
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 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?



        


5 Comments

POST Answer of Questions and ASK to Doubt

  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

Post a Comment

POST Answer of Questions and ASK to Doubt

Previous Post Next Post