Python Thread - Constructor

Method Name:

Thread Constructor

Method Overview:
 

Constructs a Thread object in Python

Parameters:

group: Represents the concept ThreadGroup. Is a reserved parameter now and will be used later implementations of Python to implement ThreadGroups.
        
target: Any Callable object. A normal function definition and passing its name here will work.  
        
name: Name of the thread. If not given it has a decimal value assigned to it by the  implementation.
        
args: It is a tuple. The reason it exists is to initialise the child thread with some data
      when it is created inside the main thread. Any complex multithreaded program will often
      use this future to pass some context from main thread to child thread. Later as the threads
      make progress, the state of this data will be used by other threads to make 
      synchronisation decisions(Whether to resume themselves, acquire more resources etc).

      
      
kwargs: This parameter serves the same purpose as the previous parameter. It helps in initialising
        the child thread with data. This parameter is a dictionary of keyword arguments.
 

daemon: This is to mention whether it is a daemon thread. Daemon threads exist even after the main thread exits. Daemon threads are very useful in certain applications. e.g., an SSH database replication thread runs behind replicating every data that enters the Database.However the program(the main thread) just starts and exits, leaving the replication thread to run forever.

Example:

from threading import Thread

 

#A function that constitutes as the thread body in python

def ThreadFunction(TupleData, KeywordDictionary):

    print("Child Thread Started")

   

    for item in TupleData:

        print(item)

 

    for key in KeywordDictionary:

        print(key+":"+KeywordDictionary[key])

 

    print("Child Thread Exiting")       

 

 

print("Main Thread Started")

#Thread initialisation data as a python tuple

ThreadData1         = ("State1", "State2", "State3")  

 

#Thread initialisation data as a python dictionary

ThreadData2         = dict([("Key1", "Value1"), ("Key2", "Value2"), ("Key3", "Value3")])

 

#Construct a python thread object and initialise with data

SamplePythonThread  = Thread(target=ThreadFunction(ThreadData1,ThreadData2),name="ChildThread")

 

#Print the name of the child thread

print("Name of the Child Thread:"+SamplePythonThread.name)

 

#Start the child thread

SamplePythonThread.start()

 

#Let the main thread wait for the child thread to complete

SamplePythonThread.join()

 

print("Main Thread Exiting")

 

PythonSystem:PythonExamples pythonuser$ python DeamonExample.py

I am the Daemon thread. I keep on running...hehe

My Daemon will take care


Copyright 2023 © pythontic.com