Python Multitasking Programming - the Use of Multiple Processes

The use of multiple processes introduction:

1. Import process package
2. Create a process
3. Start the process
4. Final implementation

1. The use of multiple processes:Import the process package



Process( [group [, target [, name [, args [, kwargs ]]]]])
The group parameter is not used, the value is always None
the target represents the calling object, that is, the task to be executed by the child's process
args represents the positional parameter tuple of the calling object, args = (1,2,'hello',)
Use multiprocessing. The process to create a process, target represents the function to be executed, you can use args to pass in a tuple, you must use commas such as
args = ('Zhangsan',) or use charges to pass in a dictionary to specify parameters by using keywords, such as kwargs ={'name':'zhangsan','age':18}

#create process
sub_process = multiprocessing.Process ( target = task ) _ _

2 The use of multiple processes:Create a process



Process( [group [, target [, name [, args [, kwargs ]]]]])
The group parameter is not used, the value is always None
target represents the calling object, that is, the task to be executed by the child process
args represents the positional parameter tuple of the calling object, args = (1,2,'hello',)
Use multiprocessing.Process to create a process, target represents the function to be executed, you can use args to pass in a tuple, you must use commas such as
args = ('Zhangsan',) or use kwarges to pass in a dictionary to specify parameters by using keywords, such as kwargs ={'name':'zhangsan','age':18}

#create process
sub_process = multiprocessing.Process ( target = task ) _ _

3 The use of multiple processes:Start the process



#start process
sub_process.start ( ) _ _

Common method
start() starts a child process instance
join() waits for the execution of the child process to end
terminate() terminates immediately regardless of whether the task is completed or not

4 The use of multiple processes:Final realization



import multiprocessing
import time

def dance():
for i in range(5):
print("dance...")
time.sleep(1)
def sing():
for i in range(5):
print("sing...")
time.sleep(1)


# Determine whether it is a directly executed module, program entry module
# Standard python writing, directly executed modules, need to add code to judge whether it is the main module
if __name__ == '__main__':
#create
dance_process = multiprocessing.Process(target=dance)
sing_process = multiprocessing.Process(target=sing)
#start up
dance_process.start()
sing_process.start()
Output result:
dance...
sing...
dance...
sing...
dance...
sing...
dance...
sing...
dance...
sing...

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00