Threading in Python

05 min read

A thread is defined to be the smallest element that can be placed in an operating system for execution. Threading is generally done in a computer program to execute two or more tasks simultaneously in a single processor through the concept of multi-tasking. For example, consider the case of two friends texting between each other, it's foolish to write a program which allows only one of them to send and another to receive at a given point in time. It's wise to develop a program where both can send and receive simultaneously. In such a case one has to use threading concept to simultaneously run the transmission code and receiving module code. 

To implement threading concept in Python, initially, we need to import the "threading" module into the script. The syntax and implementation of threading in Python are as follows:

import threading                                              #importing necessery modules
class FACEmessenger(threading.Thread):   
              def run(self):                                        # this function should always be named run, each time start() function is operated later in the program, this run function gets triggered.
                           for _ in range(10):                # for loop can be implemented in this syntax to just loop its elements 10 times without any increments in it's variables
                                       print( threading.current Thread().getname())

x= FACEmessenger (name = 'Placements')               
y = FACEmessenger(name = 'Receive')
x.start()                        # start function redirects back to class and triesto find "run" function in it.
y.start() 

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error