catalogue
1, Multithreading module: threading
5. Number of threads currently alive
Tip: the following is the main content of this article. The following cases can be used for reference
1, Multithreading module: threading
threading module is a module about multithreading that comes with python. It is easy to use and supports creating multiple threads, sharing data and locking threads.
Import module
import threading
Two, module function
1 create thread
Format:
threading.Thread(group=None,target=None,name=None,args=(),kwargs={},daemon=None)
The parameter group is used for thread grouping management, and the group name of the incoming thread. Not often.
The parameter target is used to pass in the object to be called by the thread, which can be a method or a class
Parameter name, used to pass in the name of the thread.
Parameter args is used to pass in the parameter of the calling object. The passed in must be a tuple
Parameter kwargs is the keyword parameter dictionary used to call the target function
Parameter daemon, which explicitly sets whether the thread is in daemon mode. When daemon=True is to enable the daemon mode, when the main thread ends, the created thread ends directly. When the daemon saves the default value, when the main thread ends, the created thread continues to run until it ends.
example:
import threading def task(num): #Create a method print("Successfully created 1 thread") print(f"The name of the thread is:{t.name}") print(f"The parameters passed in are:{num}") t=threading.Thread(target=task,name="download",args="8") #Create a thread t.start() #Start thread
2. Start thread
Function:
start()
When a thread is created, it is called. It can only be called once in a thread.
example:
import threading def task(): #Create a method print("Successfully created 1 thread") t=threading.Thread(target=task) #Create a thread t.start() #Start thread
3. Wait for thread
Function:
join(timeout=None)
When the thread calls the join() method
If the timeout parameter does not exist or is None, the thread calling this method will be blocked. The code behind the join() method will not be executed until the thread execution is completed.
If the timeout parameter exists and is not None, it should be a floating-point number or fraction in seconds used to specify the operation timeout.
example:
import threading from time import sleep def task(): #Create a method print("Create 1 thread\n") sleep(1) #Delay 1 second print("Thread created successfully") t=threading.Thread(target=task) #Create a thread t.start() #Start thread t.join() #Wait until the thread ends print("Thread ended")
4. Thread lock
Function:
threading.Lock()
It is used to lock a variable or other things to prevent different threads from calling the same variable at the same time. Lock() has two methods: acquire() and release(). Acquire () changes the status to locked and release () changes it to unlocked.
example:
import time import threading as tg task=100000 #Number of tasks per thread thread=10 #Number of threads num=0 #Number of tasks completed by all threads threads=[] #Used to save all threads lock=tg.Lock() #A lock (used to lock a variable or something else to prevent different threads from calling the same variable at the same time) def download(): #Create a method for the thread to call global num for i in range(task): lock.acquire() #Lock to prevent other threads from reading / modifying num +=1 #Complete 1 task, add 1 to the total lock.release() #Unlock so that other threads can read / modify for i in range(thread): t=tg.Thread(target=download) #Create thread , And pass in the method to be called by the thread threads.append(t) #Save the created thread to the list t.start() #Start thread print(tg.active_count()) for t in threads: t.join() #Wait for all threads to complete execution before executing the following code print(f"Number of tasks to be completed:{task*thread}") print(f"Number of tasks actually completed:{num}")
5. Number of threads currently alive
Format:
threading.active_count()
Returns the number of threads currently alive. The return value is consistent with the length of the list returned by enumerate().
example:
import threading from time import sleep def task(): #Create a method print("Create 1 thread\n") sleep(1) #Delay 1 second print(f"thread {t.name}Created successfully") t=threading.Thread(target=task) #Create a thread t.start() #Start thread num=threading.active_count() #Returns the number of lines currently alive print(f"Number of lines currently alive=Main thread+Created thread={num}") t.join() #Wait until the thread ends print("The thread created has ended") num=threading.active_count() #Returns the number of lines currently alive print(f"Number of lines currently alive=Main thread={num}")
Thanks for uncle Mai's programming tutorial:
Python multithreading practice_ Beep beep beep_ bilibili