× Python Introduction What is Python Python Features Python History Python Applications Python Install Python Path Python Example Execute Python Keywords Constant Variable Statements & Comments Python I/O and Import Operators UnaryBinaryTernary Unary Operators Unary Minus Binary Operators Arithmetic Operators Assignment Operators Relational Operators Logicaloperators Bitwise Operator Ternary Operators Control Statements in Python conditonal Statements IF if else Else If Nested if Switch For loop Nested For Loop While Loop Nested while Loop Unconditonal Statemets Continue Break Pass FUNCTIONS Python Function Function Argument Python Recursion Anonymous Function Python Modules NATIVE DATATYPES Python List Python Numbers Python Tuple Python String Python Set Python Dictionary OOPS PRINCIPALS Encapsulation Class Variable Method Object Or Instance CreationMethod Calling OOPS Syntax And Explanation DATA ABSTRACTION Constructor Inheritance 1.Single or simple Inheritance 2.Multilevel Inheritance 3.Hierarchical Inheritance 4.Multiple Inheritance 5.Hybrid Inheritance Operator Overloading File Operation Python Directory Python Exception Python - Multithreading Python - Database Access Python - CGI Python - Reg Exp Python - Date Python - XML Processing Python - GUI
  • iconPython Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

MULTI THREADING


Without Using Threading Rules:

Program: Display 1-10 number with 2sec time gap #!/usr/bin/python import threading import time def myfun(): counter=1 while counter<=10: time.sleep(2) print(counter) counter =counter+ 1 if __name__=="__main__": myfun()

Thread:
Thread is a flow of execution. In Python language these Threads are classified into two types
1.Single Tasking(threading)
2.Multitasking(threading)

Single Tasking(threading)

Whenever processor executing only one task (operation) is known as single tasking. The main disadvantage with single tasking is utilization of processor time is not done properly to overcome this problem multi threading was introduced.
Multitasking(threading):
Whenever multiple tasks are executing simultaneously by the processor is known as multitasking. Multitasking is classified into two ways.
1.Process based Multi Tasking
2.Thread based Multi Tasking

Process based multi threading or multi tasking:
Whenever multiple processor of different applications are running simultaneously to perform different operation by the processor is known as process based multitasking.
Example:
playing game, playing audio song,loading website in a browser etc.. it can be simultaneous by the processor.

Thread based multithreading:
Whenever same part of program or multiple parts of programs are executing simultaneously known as thread based multi tasking.
OR
Whenever multiple threads are running simultaneously is known as multithreading. Thread is a flow of execution, in real time it can be treated as request from the end user. threads are mainly classified into two types.

1.Foreground thread
2.Background thread

Foreground thread:
If any thread is running in the foreground of Python program is known as foreground thread. example: main method or main thread.

Background thread:
If any thread is running in the background of Python program is known as background thread example: garbage collector.

Thread States:
New State:
If any thread is created without allocation of memory space then the thread is comes under the new state.
Ready State:
Whenever sufficient memory is allocated for the thread and if it is ready to execute then the thread under the ready state.
Running State:
Whenever a thread is under execution then that can be treated as running state.
Waiting state:
if any thread execution is stopped temporary is known as waiting state.
Dead state:
If any thread execution is stopped permanently then that is comes under the dead state.

NOTE:
Whenever thread is in either new or dead state no memory is available and it remaining three cases (ready, running, waiting) sufficient memory is allocated. In realtime multithreading can be used either to design server softwares or different gaming softwares etc….

Types of threads:
In Python language threads are classified into two types.
1.Predefined thread
2.User defined thread
Predefined thread:
If any thread is already designed by Python developers is known as predefined thread.
Example: main thread, garbage collector , etc…..

User defined thread: If any thread is designed by the Programmer is known as user defined thread.

Key Points

Image






Thread classs

Rules to create a user defined thread :
1.Create a user defined class and extends thread class
2.create a constructor and call the predefined thread class constructor
3.Override run method of super class into user defined thread class.
4.Create an object (thread) for the user defined class.
5.Call run method with the help of start method.
Syntax:
class Mythread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
		Def run(self):
			….
			….
			….

if __name__=="__main__":     
    m=Mythread()
    m.start()



Write a Python program to display message a 2sec time gap.
#!/usr/bin/python import threading import time class myThread (threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): counter=1 while counter<=10: time.sleep(2) print(counter,self.name) counter =counter+ 1 if __name__=="__main__": thread1 = myThread() # Start new Threads thread1.start()

Output:
1 Thread-1
2 Thread-1
3 Thread-1
4 Thread-1
5 Thread-1
6 Thread-1
7 Thread-1
8 Thread-1
9 Thread-1
10 Thread-1
write a Python program to achieve multithreading with respective to user defined thread.(addition and substraction program)


#!/usr/bin/python
import threading
import time

class thDemo(threading.Thread):  
    def run(self):
        x=10
        y=20
        z=x+y
        print(z)
        time.sleep(2)
        z=x-y
        print(z)
              
if __name__=="__main__":
    t=thDemo()
    t.start()
    
                                

Output:

Thread class methods:

run() − The run() method is the entry point for a thread.

start() − The start() method starts a thread by calling the run method.

join([time]) − The join() waits for threads to terminate.

isAlive() − The isAlive() method checks whether a thread is still executing.

getName() − The getName() method returns the name of a thread.

setName() − The setName() method sets the name of a thread.

Key Points

Image
Thread Synchronization or thread safe:

The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock. If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released. The release() method of the new lock object is used to release the lock when it is no longer required.



Without synchronized
#!/usr/bin/python import threading import time a=1 class myThread (threading.Thread): def __init__(self,name): threading.Thread.__init__(self) def run(self): w=1; global a print("Available are ", a) if(a>=w): print(w,"reserverd ",self.name) a=a-w; time.sleep(2) else: print("sorry!....no tickets avalavle"); # Create new threads if __name__=="__main__": thread1 = myThread("t1") thread2 = myThread("t2") thread3 = myThread("t3") # Start new Threads thread1.start() thread2.start() thread3.start()

Output:
Available are Available are Available are 111 111 reserverd reserverd reserverd Thread-1Thread-2Thread-3
With synchronizing concept



#!/usr/bin/python

import threading
import time
a=1
class myThread (threading.Thread):
   def __init__(self,name):
      threading.Thread.__init__(self)
      
   def run(self):
      w=1;
      global a
   
      threadLock.acquire()
      print("Available are ", a)
      
      if(a>=w):
          a=a-w;
          print(w,"reserverd  ",self.name)
          time.sleep(2)
      else:
          print("sorry!....no tickets avalavle");
      threadLock.release()
      


threadLock = threading.Lock()
#threads = []
if __name__=="__main__":  
    # Create new threads
    thread1 = myThread("t1")
    thread2 = myThread("t2")
    thread3 = myThread("t3")

    # Start new Threads
    thread1.start()
    thread2.start()
    thread3.start()








                                

Output:
Available are 1
1 reserverd Thread-1
Available are 0
sorry!....no tickets avalavle
Available are 0
sorry!....no tickets avalavle