Process类语法详解

发布时间 2023-07-23 17:32:45作者: Allen_Hao
'''
multiprocessing.Process 类是 multiprocessing 模块中用于创建和管理进程的主要类。它提供了一系列方法和属性,用于控制和监视进程的行为。
1. 创建 Process对象:
    语法: p = Process(target=func, args=(args,), kwargs={})
    1. target:指定要在新进程中执行的任务即函数或可调用对象。
    2. args:传递给目标函数的位置参数,以元组的形式传入。
    3. kwargs:传递给目标函数的关键字参数,以字典的形式传入。

2. 启动进程: p.start()
   创建Process对象并指定任务,调用 start() 方法来启动新进程执行任务

3. 阻塞等待进程结束: p.join()
    调用join()方法来阻塞当前进程,直到子进程执行完毕。即哪个进程执行了p.join(),那么该进程就得等p进程执行完成。

4. 判断进程是否存活: p.is_alive()
    调用is_alive() 方法来判断进程是否仍在运行。

5. 终止进程: p.terminate()
    调用terminate()方法来终止进程的执行。

6. 获取进程 ID: p.pid
    pid 属性返回进程的 ID。

7. 设置进程名称: p.name = "process_name"
    可以通过设置 name 属性来为进程指定一个名称。

8. 获取当前进程对象: multiprocessing.current_process()
    调用 current_process() 函数返回当前进程的 Process 对象。

9. 获取父进程 ID: p.ppid()
    ppid() 方法返回父进程的 ID。

10. 传递共享数据给子进程:
    multiprocessing.Manager().Value()
    multiprocessing.Manager().Array()
    使用 multiprocessing.Manager() 创建一个管理器对象,然后可以使用 Value() 和 Array() 方法创建可在多个进程之间共享的变量和数组。



'''
import multiprocessing
from multiprocessing import Process



def square(x):
    result = x * x
    print(f"The square of {x} is {result}")


if __name__ == '__main__':
    # 创建 Process 对象并指定任务
    p1 = Process(target=square, args=(5,))
    p2 = Process(target=square, args=(10,))

    # 启动进程执行任务
    p1.start()
    p2.start()

    # 阻塞等待进程结束
    p1.join()
    p2.join()

    # 判断进程是否存活
    if p1.is_alive():
        print("p1 is still running")
    else:
        print("p1 has finished")

    if p2.is_alive():
        print("p2 is still running")
    else:
        print("p2 has finished")

    # 获取进程 ID
    print("Process ID of p1:", p1.pid)
    print("Process ID of p2:", p2.pid)

    # 设置进程名称
    p1.name = "Square process 1"
    p2.name = "Square process 2"

    print("Name of p1:", p1.name)
    print("Name of p2:", p2.name)

    # 获取当前进程对象
    current_process = multiprocessing.current_process()
    print("Current process name:", current_process.name)
    print("Current process ID:", current_process.pid)

输出:

 1 The square of 5 is 25
 2 The square of 10 is 100
 3 p1 has finished
 4 p2 has finished
 5 Process ID of p1: 1860
 6 Process ID of p2: 2116
 7 Name of p1: Square process 1
 8 Name of p2: Square process 2
 9 Current process name: MainProcess
10 Current process ID: 15808
传递共享数据给子进程示例:
 1 from multiprocessing import Process, Manager
 2 
 3 
 4 def worker(shared_list):
 5     shared_list.append("data from child process")
 6 
 7 
 8 if __name__ == '__main__':
 9     with Manager() as manager:
10         # 创建共享的列表对象
11         shared_list = manager.list(["data from main process"])
12 
13         # 创建子进程,并将共享的列表对象传递给子进程
14         p = Process(target=worker, args=(shared_list,))
15         p.start()
16         p.join()
17 
18         # 打印共享的列表对象内容
19         print(shared_list)
20 '''
21 1. 使用 Manager() 创建了一个管理器对象 manager。然后,通过调用 manager.list() 方法创建了一个共享的列表对象 shared_list,初始值为 ["data from main process"]。
22 
23 2. 接着,我们创建了一个子进程 p,并将 shared_list 作为参数传递给子进程的任务函数 worker。在子进程中,我们向 shared_list 中添加了一个元素 "data from child process"。
24 
25 3. 最后,在主进程中,我们打印了 shared_list 的内容,可以看到它已经被子进程修改为 ["data from main process", "data from child process"]。
26 
27 运行以上代码,会输出如下结果: ['data from main process', 'data from child process']  说明主进程与子进程共享shared_list
28 
29 '''