How can I use threading in Python?

前端 未结 19 3102
迷失自我
迷失自我 2020-11-21 04:54

I am trying to understand threading in Python. I\'ve looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I\'m having trou

19条回答
  •  孤城傲影
    2020-11-21 05:21

    Here is multi threading with a simple example which will be helpful. You can run it and understand easily how multi threading is working in Python. I used a lock for preventing access to other threads until the previous threads finished their work. By the use of this line of code,

    tLock = threading.BoundedSemaphore(value=4)

    you can allow a number of processes at a time and keep hold to the rest of the threads which will run later or after finished previous processes.

    import threading
    import time
    
    #tLock = threading.Lock()
    tLock = threading.BoundedSemaphore(value=4)
    def timer(name, delay, repeat):
        print  "\r\nTimer: ", name, " Started"
        tLock.acquire()
        print "\r\n", name, " has the acquired the lock"
        while repeat > 0:
            time.sleep(delay)
            print "\r\n", name, ": ", str(time.ctime(time.time()))
            repeat -= 1
    
        print "\r\n", name, " is releaseing the lock"
        tLock.release()
        print "\r\nTimer: ", name, " Completed"
    
    def Main():
        t1 = threading.Thread(target=timer, args=("Timer1", 2, 5))
        t2 = threading.Thread(target=timer, args=("Timer2", 3, 5))
        t3 = threading.Thread(target=timer, args=("Timer3", 4, 5))
        t4 = threading.Thread(target=timer, args=("Timer4", 5, 5))
        t5 = threading.Thread(target=timer, args=("Timer5", 0.1, 5))
    
        t1.start()
        t2.start()
        t3.start()
        t4.start()
        t5.start()
    
        print "\r\nMain Complete"
    
    if __name__ == "__main__":
        Main()
    

提交回复
热议问题