Concurrency: Refers to the ability of the system to handle multiple tasks (the CPU is switching to complete concurrency), and concurrency is a subset of parallelism.
Parallelism: Refers to the ability of a system to handle multiple tasks simultaneously (actions)
Processes and Threads:
A task is a process, such as open a browser, open a QQ is also a process. , all the data resources of the program are stored here. Process is the smallest resource snap-in
Threads are process-based, and a process has at least 1 threads, and the code is the smallest execution unit in a thread, such as when you send a message, a file, and so on.
A thread is a memory unit of a shared process, so multiple threads implement resource sharing.
One thread can create or revoke another thread, then this thread is called the parent thread. Other
Multiple threads in the same process can execute concurrently (there is a CPU switchover) and cannot be executed in parallel. This is because Python has a global interpreter lock, and at some point, only 1 threads of an application can use the CPU.
1, create multi-process
Import Multiprocessingimport threadingimport timedef Worker (id,interval): print (' Start work {0} '. Format (ID)) time.sleep (interval) print (' End work {0} '. Format (ID)) def main (): print (' Start main ') p1 = Multiprocessing. Process (target=worker,args=) P2 = multiprocessing. Process (target=worker,args= (2,2)) p3 = multiprocessing. Process (target=worker,args= (3,3)) P1.start () # Print (p1.pid) P2.start () # print (p2.pid) P3.start () # Print (p3.pid) print (' end Main ') if __name__ = = ' __main__ ': Main ()
‘‘‘
Target refers to the content that the newly derived child process needs to process
Args is the parameter passed to the function, and args must be a tuple. If you are passing in a single element, you must also be a tuple.
P represents a multi-process, run indicates the START process, start is also the START process, he essentially calls the Run method. It is recommended that start
P.is_alive () Determine if the process is alive
P.run () START process
P.name () The name of the output process
PID of the P.pid () process
P.join (timeout) waits for the child process to end or to a time-out
P.terminate forcing a child process to exit
‘‘‘
Import Multiprocessingimport threadingimport timedef Worker (id,interval): print (' Start work {0} '. Format (ID)) time.sleep (interval) print (' End work {0} '. Format (ID)) def main (): print (' Start main ') p1 = Multiprocessing. Process (target=worker,args=) P2 = multiprocessing. Process (target=worker,args= (2,2)) p3 = multiprocessing. Process (target=worker,args= (3,3)) P1.start () p1.join (1) #等待p1进程执行1s, the code continues to execute regardless of whether the P1 execution is complete. P2.start () P3.start () for p in Multiprocessing.active_children (): #查看当前存活的进程 Print ( P.name) print (' end Main ') if __name__ = = ' __main__ ': Main ()
Python Multi-process