Learn Python together: thread

Posted by Toshiba23 on Sun, 19 Jul 2020 18:09:13 +0200

thread

The thread module of python is a lower level module, and the threading module of python is a package for thread, which can be used more conveniently

  1. Using the threading module

Single thread execution


#coding=utf-8
import time

def saySorry():
    print("Honey, I'm wrong. Can I eat now?")
    time.sleep(1)

if __name__ == "__main__":
    for i in range(5):
        saySorry()

Operation results:


Picture.png

Multithreading execution

#coding=utf-8
import threading
import time

def saySorry():
    print("Honey, I'm wrong. Can I eat now?")
    time.sleep(1)

if __name__ == "__main__":
    for i in range(5):
        t = threading.Thread(target=saySorry)
        t.start() #Start the thread, that is, let the thread start execution

Operation results:


Picture.png

explain

It can be seen that the use of multithreaded concurrent operations takes much less time
When start() is called, the thread is actually created and executed

  1. The main thread will wait for all child threads to finish
#coding=utf-8
import threading
from time import sleep,ctime

def sing():
    for i in range(3):
        print("Singing...%d"%i)
        sleep(1)

def dance():
    for i in range(3):
        print("Dancing...%d"%i)
        sleep(1)

if __name__ == '__main__':
    print('---start---:%s'%ctime())

    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)

    t1.start()
    t2.start()

    #sleep(5) # Block this line of code, try to see if the program will end immediately?
    print('---end---:%s'%ctime())
  1. View number of threads
#coding=utf-8
import threading
from time import sleep,ctime

def sing():
    for i in range(3):
        print("Singing...%d"%i)
        sleep(1)

def dance():
    for i in range(3):
        print("Dancing...%d"%i)
        sleep(1)

if __name__ == '__main__':
    print('---start---:%s'%ctime())

    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)

    t1.start()
    t2.start()

    while True:
        length = len(threading.enumerate())
        print('The number of threads currently running is:%d'%length)
        if length<=1:
            break

        sleep(0.5)

=======================================================

The above contents are from my course notes. If you need to reprint or complete the notes, please contact me on wechat.

Since today, Python has updated my learning notes every day. Official account dry cargo is updated continuously.

Link to the original text: python developer communication platform

Topics: Python less