Hola!

You've found my spot on the internet that's all about me. I put together this little site to show off my work and keep track of my various projects.

Threading in Python

Threading has been very helpful in some situations. Here’s how I implemented it in my recent project. I’m posting it here as a reference.

import threading, Queue

#Create the queue for threading
queue1 = Queue.Queue()

class thread_cmm_scan(threading.Thread):
    def __init__(self, queue1):
        threading.Thread.__init__(self)
        self.queue1 = queue1
            
    def run(self):            
        while True:
            try:
                item = self.queue1.get()
                #This is the function that I have firing each time a new task in the queue is ready.
                single_chassis_update(item)
                self.queue1.task_done()
            except:
                break

def rsl_flex_update(new_cmm_IP):    
    #Get a list of chassis from the database
    list_of_chassis = Chassis.objects.filter(Enabled=True)
    
    #Create a certain number of threads
    for x in range(10):
        t = thread_cmm_scan(queue1)
        t.setDaemon(True)
        t.start()
    
    #Loop through each chassis and add it to the queue
    for chassis in list_of_chassis:
        queue1.put(chassis.address)
        
    queue1.join()

Leave a Reply

Your email address will not be published. Required fields are marked *