Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Synchronizing Threads in Python

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 455
    Comment on it

    With the help of threading module we can implement locking mechanism that allows you to synchronize threads. And a new lock is created by calling the Lock() method, which returns the new lock and thread in threads module.
    For example you can see below code .

    #!/dinesh/bin/python
    import threading
    import time
    class myThread (threading.Thread):
        def __init__(self, threadID, test, counter):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.counter = counter
        def run(self):
            print "Starting " + self.test
            # Get lock to synchronize threads
            threadLock.acquire()
            print_time(self.name, self.counter, 3)
            # Free lock to release next thread
            threadLock.release()
    
    def print_time(threadName, delay, counter):
        while counter:
            time.sleep(delay)
            print "%s: %s" % (threadtest, time.ctime(time.time()))
            counter -= 1
    
    threadLock = threading.Lock()
    threads = []
    
    # Create new threads
    thread1 = myThread(1, "test-1", 1)
    thread2 = myThread(2, "demo-2", 2)
    
    # Start new Threads
    test1.start()
    demo2.start()
    
    # Add threads to thread list
    threads.append(test1)
    threads.append(demo2)
    
    # Wait for all threads to complete
    for t in threads:
        t.join()
    print "Exiting Main Thread"
    

 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: