Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the process module of python

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use the process module of python". In the daily operation, I believe many people have doubts about how to use the process module of python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the process module of python". Next, please follow the editor to study!

Process module

The process module is a module that creates a process, and with this module, the process can be created.

Parameter description:

Process (group=None, target=None, name=None, args= (), kwargs= {}) 1 group-- parameter is not used, and the value is always None2 target-- to indicate the calling object, that is, the task to be executed by the child process 3 args-- represents the location parameter tuple of the calling object, args= (1 kwargs-- 2 kwargs-- represents the dictionary of the calling object, and kwargs= {'name':'egon','age':18} 5 name-- is the name of the child process

Method introduction:

Obj.start (): start the process and call obj.run () obj.run () in the child process. It is the method that runs when the process starts, which calls the function specified by target. The method obj.terminate () must be implemented in the class of our custom class: the process obj is forcibly terminated without any cleanup operation. If obj creates a child process, the child process becomes a zombie process. Using this method requires special care in this case. If obj also holds a lock, it will not be released, resulting in a deadlock obj.is _ alive (): if obj is still running, return Trueobj.join ([timeout]): the main thread waits for obj to terminate (emphasize: the main thread is in a waiting state, while obj is running). Timeout is an optional timeout. It should be emphasized that obj.join can only join processes started by start, but cannot join processes started by run.

Property description:

Obj.daemon: the default value is False. If it is set to True, it means that obj is a daemon running in the background. When the parent process of obj terminates, obj also terminates, and after it is set to True, obj cannot create its own new process. You must set obj.name: process name obj.pid: process pidobj.exitcode: process is None at run time, if-N Indicates that the authentication key of the obj.authkey: process is terminated by signal N, and the default is a 32-character string randomly generated by os.urandom (). The purpose of this key is to provide security for underlying inter-process communication involving network connections This kind of connection can be successful only if it has the same authentication key. 1. Start a child process in python from multiprocessing import Processimport osdef func (): print ('this is a child process-- > process number:', os.getpid (), 'main process number:', os.getppid ()) if _ _ name__ = ='_ _ main__': print ('this is the main process-- > process number:', os.getpid () 'Master process number (pycharm):' Os.getppid () # instantiate a child process object obj = Process (target=func) obj.start () # execute the child process object print ('finished executing the contents of the main process') # output this is the main process-- > process number: 3100 main process number (pycharm): 6748 finished executing the contents of the main process this is a child process-- > process number: 2392 main process number: 31002, Pass the parameter from multiprocessing import Processimport osdef func (name) to the child process Age): print ('this is a child process-- > process number:', os.getpid (), 'main process number:', os.getppid () print (f' this is a child process-- > my name is {name} This year {age}') if _ _ name__ = ='_ _ main__': print ('this is the main process-- > process number:', os.getpid (), 'main process number (pycharm):', os.getppid ()) # instantiate a child process object obj = Process (target=func, args= ('Xiao Yang') ('18')) # args passes position parameters to child process func functions in tuples # kwargs passes keyword arguments # kwargs= {' name': 'Xiao Yang' to child process func functions in dictionary form 'age': 18} obj.start () # execute child process object print (' finished executing the contents of the main process') # output this is the main process-- > process number: 11936 main process number (pycharm): 3676 finished executing the contents of the main process-- this is a child process-- > process number: 2996 main process number: 11936 this is a child process-- > my name is Xiao Yang This year, multiple sub-processes from multiprocessing import Processimport osdef func (name, age): print (f' this is a child process-- > process number: {os.getpid ()}, main process number: {os.getppid ()}, my name is {name} This year {age}') if _ _ name__ = ='_ _ main__': print ('this is the main process-- > process number:', os.getpid (), 'main process number (pycharm):', os.getppid ()) count = [('Xiao Yang', 18), ('Bob', 20), ('Allen' 55)] for lis in count: # instantiate a child process object obj = Process (target=func Args=lis) # args passes the location parameter obj.start () # executes the child process object print ('finished executing the contents of the main process') # output this is the main process-- > process number: 12632 main process number (pycharm): 9220 finished executing the contents of the main process-- this is a child process-- > process number: 10048, main process number: 12632 My name is Xiao Yang This year 18 this is a child process-- > process number: 16032, main process number: 12632, my name is Bob, this year 20 this is a child process-- > process number: 12060, main process number: 12632, my name is Allen.

Obj.join ([timeout]): the main process waits for the child process obj to terminate (emphasis: the main process is in the wait state, while the child process obj is in the running state). Timeout is an optional timeout. It should be emphasized that obj.join can only join processes started by start, but cannot join processes started by run.

Multiple processes are running at the same time (note that the execution order of child processes is not determined by the startup order)

Join-- > belongs to synchronous blocking:

Synchronization: initiate event B when doing event A, and you must wait for event B to finish before you can continue to do event A.

Blocking: CPU does not work-- > input accept recv recvfrom sleep connect.

Start-- > belongs to asynchronous non-blocking:

Async: initiates event B when doing event A, and you can continue event A without waiting for event B to finish.

Non-blocking: CPU in operation (non-input / output phase I / stroke O)

From multiprocessing import Processimport randomimport timedef mail (name, age): count = random.random () print (f' sent an email to {age} year old {name}! Delay {count} seconds') time.sleep (count) # simulate network delay "" multiple processes are running simultaneously (note The execution order of child processes is not determined by the startup order) "" if _ _ name__ ='_ _ main__': info_list = [('Xiao Yang', 18), ('Bob', 20), ('Allen', 55)] jo = [] for info in info_list: obj = Process (target=mail) Args=info) obj.start () jo.append (obj) # put all child processes in the jo list In the loop join all the child processes, you can wait for all the child processes to finish after doing the operation for oin jo: o.join () # all the child processes end the operation print ('all sent') # the output sends an email to 20-year-old Bob! Delay 0.19840279388911186 seconds sent an email to 18-year-old Xiao Yang! Delay 0.8891892863366903 seconds sent an email to 55-year-old Alan! The delay is 0.0434307277609951 seconds. Whether the data between multiple processes is isolated from multiprocessing import Processcount = 1def func (): global count count + = 1if _ _ name__ ='_ _ main__': for i in range (10): obj = Process (target=func) obj.start () print (count) #-> 1 the count of the main process is not changed indicating that the data between processes is not changed. Why must Process () be placed under if _ _ name__ ='_ _ main__': in Windows

Since Windows does not have fork, the multiprocessing module starts a new Python process and imports the calling module.

If Process () is called on import, this will start a new process that inherits infinitely (or until the machine runs out of resources).

This is the source that hides the internal call to Process (), and statements in the if statement using if _ _ name__ = ='_ _ main__':, will not be called on import.

At this point, the study on "how to use the process module of python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report