子进程产生了多少个问题?

时间:2019-04-09 11:33:13

标签: python-3.x while-loop multiprocessing

我有以下代码:

import multiprocessing
import os

def info(title):
    print("~"*50)
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def foo():
    info("foo()")
    print("bar")

if __name__ == '__main__':
    while True:
        p = multiprocessing.Process(target=foo)
        p.start()
        p.join()
        time.sleep(1)

对于我想做的事情,它就像一种魅力。当我观察到正在执行的脚本时,PID的确很高。

示例输出:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
foo()
module name: __main__
parent process: 1104
process id: 4805
bar
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
foo()
module name: __main__
parent process: 1104
process id: 4806
bar

但是,通过top看到的PID并未更改:

 1104 x3         20   0 60060 18252  8560 S  0.7  1.9  0:20.55 │           └─ python3 clockMatrix7219.py
 1109 x3         20   0 60060 18252  8560 S  0.0  1.9  0:00.00 │              ├─ python3 clockMatrix7219.py
 1108 x3         20   0 60060 18252  8560 S  0.0  1.9  0:00.00 │              ├─ python3 clockMatrix7219.py
 1107 x3         20   0 60060 18252  8560 S  0.0  1.9  0:00.00 │              ├─ python3 clockMatrix7219.py
 1106 x3         20   0 60060 18252  8560 S  0.0  1.9  0:00.00 │              └─ python3 clockMatrix7219.py

clockMatrix7219.py是脚本的名称。

我的问题是:将来会出现问题吗?会有限制吗?因为该脚本旨在始终运行。同样,每个过程仅运行一秒钟的时间,然后完成。

非常感谢!

1 个答案:

答案 0 :(得分:0)

响应为零,但我想出了如何避免在每个循环中扩展新进程的方法。

我只是将while loop放在函数中。

import multiprocessing
import os

def info(title):
    print("~"*50)
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def foo():
    while True:
        info("foo()")
        print("bar")

if __name__ == '__main__':
    p = multiprocessing.Process(target=foo)
    p.start()
    p.join()
    time.sleep(1)
相关问题