How do I use multithreading?
practical example
Due to the global interpreter lock (GIL) in python, only one thread is allowed to run in the interpreter at any given moment.
Thus python's multithreading is not suitable for cpu-intensive tasks.
Those who want to handle cpu-intensive tasks can use a multi-process model.
prescription
Using the standard library, it can start sub-processes to perform tasks, operating interfaces, inter-process communication, inter-process synchronization, etc., are similar to.
Code Demo
(1) Simple use of processes
# _*_ encoding:utf-8 _*_ from multiprocessing import Process # Define functions that need to be executed by child processes def f(s): print(s) # Create a global variable x = 1 # Modify the value of a global variable inside the f2 function def f2(): # Use global to declare x, then modify it to 5 global x x = 5 if __name__ == '__main__': # Create sub-processes to execute functions p = Process(target=f, args=('hello',)) # Launch sub-processes () # Waiting for a process to end () ''' Unlike multithreading multiple processes are independent of each other in terms of the virtual address space they use. ''' # Call f2 in this process and then look at x and see that it becomes 5 f2() print(x) # Change x back again, start a sub-process to change it. x = 1 p1 = Process(target=f2) () # Check if x is 1 or 5 in the main process # print(x) # Finding x=1 means that the child process and the master process are not seeing the same x. They are independent. # Since processes cannot access each other's address space,How processes communicate with each other
(2) Queue queue and Pipe pipe simple to use
# _*_ encoding:utf-8 _*_ from multiprocessing import set_start_method # Import processes, queues and pipelines from multiprocessing import Process, Queue, Pipe # Note that Queue and are not the same object # q = Queue() (1) print(()) def f(q1): print('start') # Waiting for the master process to pass in a value print(()) print('end') # Pipe creates bi-directional pipes c1, c2 = Pipe() # Pass in data to c1 end of pipe, read it out at c2 end ('abc') print(()) # Written on c2, read from c1 # ('xyz') print(()) def f2(c): # Read the data from the connection and multiply by 2 and write it back (() * 2) if __name__ == '__main__': ''' set_start_method for process creation: fork for branch creation, spawn for spawn creation. ''' set_start_method('fork', True) # ------------------------------ q2 = Queue() # Start a child process and run it directly Process(target=f, args=(q2,)).start() # Subprocesses block to get, waiting for a value to be passed in (100) # ------------------------------ c3, c4 = Pipe() # The child process will wait to write to the pipe Process(target=f2, args=(c4,)).start() # Write data from c3, then the function returns back and reads it again on c3 (55) print(())
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.