What is the difference between python thread execution program and function execution program

The fundamental difference is : multi-threaded programs are not blocked, but concurrent.
The ordinary program is carried out in accordance with the traditional process, if you encounter while (true) in the middle, then the program will always be in this endless loop, and will never go down. The multithreaded program does not, it is concurrent. In the next time slice of the CPU, the multi-threaded program will execute its own thing, regardless of the infinite loop you have here.

Take the code as an example:
1. Use ordinary functions to execute the program

import threading
import time


def tt1():
    while 1:
        print('hello')
        time.sleep(0.1)


def tt2():
    print('hello world')


if __name__ == '__main__':
    # t1 = threading.Thread(target=tt1).start()
    tt1()
    tt2()
    pass

Print result:
Insert picture description here
Run the program, the program will create a process with a main thread, and the main thread will execute the tt1() function. Due to the use of an infinite loop, it will always be blocked and the program cannot continue to execute downwards.
2. Use threads to execute programs:

import threading
import time


def tt1():
    while 1:
        print('hello')
        time.sleep(0.1)


def tt2():
    print('hello world')


if __name__ == '__main__':
    t1 = threading.Thread(target=tt1).start()
    # tt1()
    tt2()
    pass

Running result:
Insert picture description here
'hello world' is printed out, indicating that the main program is not blocked, but waiting for the CPU to be idle, switching back to the main thread and continuing to execute the program. Printing'hello world'
Description: The program will create a process, process It has a main thread, which will execute the program. After execution, the program creates a t1 sub-thread, and the CPU will switch to the function tt1() for execution, until the CPU switches back to the main program and executes the tt2() function, printing hello world( (CPU switching is due to python GIL lock)

Summary :
1. Generally, if you want to use multiple functions in a program, it is best to start the program with a thread
. Each function uses a thread . 2. The function startup program will not continue to execute when an infinite loop occurs, causing the program to block. , And thread execution of the program will not cause the main program to block, thereby achieving the effect of concurrency, and will be automatically destroyed at the end of execution, and will not occupy too much memory.

Guess you like

Origin blog.csdn.net/qq_43030934/article/details/106575546