Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Creating Thread Using Threading Module in Python

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 353
    Comment on it

    If you want to implement a new thread using the threading module, you have to follow the following steps which is given below
    Step-1 Define a new subclass of the Thread class.
    Step-2 Override the __init__(self [,args]) method to add additional arguments.
    Step-3 Then, override the run(self [,args]) method to implement what the thread should do when started.

    Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls run() method.
    For example you can see below code:

    #!/Dinesh/bin/python
    import threading
    import time
    exitFlag = 0
    class myThread (threading.Thread):
        def __init__(self, threadID, name, counter):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.counter = counter
        def run(self):
            print "Starting " + self.name
            print_time(self.name, self.counter, 5)
            print "Exiting " + self.name
    
    def print_time(threadName, delay, counter):
        while counter:
            if exitFlag:
                threadName.exit()
            time.sleep(delay)
            print "%s: %s" % (threadName, time.ctime(time.time()))
            counter -= 1
    
    # Create new threads
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
    
    # Start new Threads
    thread1.start()
    thread2.start()
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: