Want to take advantage of CPU multi-core resources
This article introduces the relevant knowledge of "want to make use of CPU multi-core resources". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Outline
Reasons for using multiple processes
Two ways to create multiple processes
Daemon process
Reasons for using multiple processes
Because multi-threading in python cannot take advantage of multi-core, if you want to take advantage of CPU multi-core resources, you need to use multi-processes.
Create multiple processes
Process ([target [, args [, name [, kwargs])
# target indicates the tasks to be performed by the child process
# args tuple parameters
# kwargs dictionary parameters
# name indicates the name of the child process
# method 1: import time from multiprocessing import Process def run (name): print ('{0} start running '.format (name)) time.sleep (2) print (' {0} run end '.format (name)) p1 = Process (target=run, args= (' Xiaohua',)) p2 = Process (target=run, args= ('Xiaomi',)) p3 = Process (target=run, args= ('small medium',) p1.start () p2.start () p3.start ()
Method one demonstration result
# method 2: import time from multiprocessing import Process class Run (Process): def _ _ init__ (self Name): Process.__init__ (self) self.name = name def run (self): print ('{0} start running '.format (name)) time.sleep (2) print (' {0} end of running '.format (name)) p1 = Run (' Xiaohua') p2 = Run ('millet') p3 = Run ('small medium') p1.start () p2.start () p3.start ()
Method two demonstrates the result.
Daemon process
The daemon terminates after the execution of the main process code. If the task of a child process is no longer necessary after the end of the main process task, then the child process should be set as a daemon before it is started. The main process code ends and the daemon terminates.
Enable time.sleep (3) and comment after two kinds of result demonstration
"want to take advantage of CPU multi-core resources" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!