Python's threading module

 

To introduce the concept of multithreading, here is an example:

import time, datetime

startTime = datetime.datetime(2024, 1, 1, 0, 0, 0)
while datetime.datetime.now() < startTime:
    time.sleep(1)

print('Program now starting on NewYear2024')

While waiting for the loop call to time.sleep() to complete, the program can't do anything, it's just there until Halloween 2029. This is because a Python program has only one thread of execution by default.

thread of execution

When downloading files, in a program that can only download one file at a time, only one file can be downloaded in the download task in the same time period, which is a single thread. An example image is as follows:

 In a program that can download two or more files at the same time, the download task in the same time period can be executed to download multiple files at the same time, which is multi-threading. An example image is as follows:

 threading module

In the above code, in order not to have to wait until the time.sleep() function completes, you can use the threading module in Python to execute the delayed or scheduled code in a separate thread. The program can do other work in the original thread at the same time.
Here is a simple sample code:

import threading, time

print('Starting of program.')

def takeANap():
    time.sleep(10)
    print('Wake up!')

threadObj = threading.Thread(target=takeANap)
threadObj.start()

print('End of program.')

The result of running the code is:

 After 10 seconds, the running result is:

Because def takeANap() defines a function that is expected to be used in a new thread, there are two threads in the code at this time, the first one is print('Starting of program.'), and there is print('End of program.') in this thread .'), execute first and end.

The thread where the takeANap() function is located is created when threadObj.start() is called, starts at the beginning of the takeANap() function, and ends after takeANap() returns.

A Python program does not terminate until all of the program's threads have ended. The second thread still executes the time.sleep(10) call after the first thread finishes.

Pass arguments to the thread's target function

If the target function that you want to run in the new thread has parameters, you can pass the parameters of the target function to threading.Thread(). For example, suppose the following print() call is run in a thread:

print('Cats', 'Dogs', 'Frogs', sep=' & ')

 The print() call has 3 regular arguments: 'Cats', 'Dogs' and 'Frogs', and a keyword argument sep=' & '.

Regular arguments can be passed as a list to the args keyword argument in threading.Thread(). Keyword parameters can be passed as a dictionary to the kwargs keyword parameter in threading.Thread(), the code is as follows:

import threading
threadObj = threading.Thread(target=print, args=['Cats', 'Dogs', 'Frogs'], 
kwargs={'sep': ' & '})
threadObj.start()

 Note: When calling threading.Thread(), the keyword parameter is target=print, not target=print(), which calls the print function itself instead of calling print(), and passes in its return value, otherwise print( ) will return None.


 

Guess you like

Origin blog.csdn.net/shufenanbei/article/details/131997837