Reproduced from: Original: Https://liangxiansen.github.io/2016/08/08/python process thread and coprocessor/author: Liang
Python Threads
The threading module in Python is used to provide threading-related operations, and threads are the smallest unit of work in an application and are good at IO operations
Import Threading
Import Time
# Create a Task
def show (ARG):
time.sleep (1)
print (' Thread ' +str (ARG))
# Loop to create 10 threads to execute this task
for the I in range:
# Create Thread, target= function, execute this function args= parameter, give this function the parameter
t = Threading. Thread (target=show, args= (i,))
# Run Threads
t.start ()
print (' main thread stop ')
The above code creates 10 "foreground" threads, and then the controller is handed over to the CPU,CPU according to the specified algorithm for scheduling, fragment execution instructions.
More methods: start
Thread is ready to wait for CPU dispatch SetName
Set the name for the thread getName
Gets the thread name Setdaemon
Set as background thread or foreground thread (default) if it is a background thread, the main thread in the process of execution, background threads are also in progress, after the main thread execution, the background thread whether successful or not, all stop if it is the foreground thread, the main thread in the execution process, the foreground threads are also in progress, after the main thread execution, When the foreground thread is finished, the program stops the join
Executes each thread one by one, and continues to execute after execution, which makes multithreading meaningless run
The thread object's Run method is automatically executed by the CPU after it is dispatched. Create a thread class yourself
# Create a thread class of your own, inheriting threading. Thread class, overriding the Run method, and the start () method calls the internal run () method