为什么多处理模块没有产生预期的结果?

Why is multiprocessing module not producing the desired result?

import multiprocessing as mp
import os

def cube(num):
    print(os.getpid())
    print("Cube is {}".format(num*num*num))

def square(num):
    print(os.getpid())
    print("Square is {}".format(num*num))

if __name__ == "__main__":
    p1 = mp.Process(target = cube, args = (3,))
    p2 = mp.Process(target = square, args = (4,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print("Done")

我正在使用 multiprocessing 模块,但我无法使用该模块打印函数的任何输出。

我什至尝试使用 sys 模块刷新 stdout

Q : "Why is multiprocessing module not producing the desired result?"

为什么?

因为它崩溃了。

问题的MWE/MCVE-representation代码有误。它崩溃并且与 sys.stdout.flush() 无关:

>>> cube(  4 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cube
NameError: global name 'os' is not defined

解决方案:

>>> import os   # be it in the __main__ or in the def()-ed functions...

>>> cube(  4 )
14165
Cube is 64

并且您基于 mp.Process() 的 python 进程实例的副本也将停止崩溃。


有效的 MCVE :

(base) Fri May 29 14:29:33 $ conda activate py3
(py3) Fri May 29 14:34:55 $ python Whosebug_mp.py
This is ____6745::__main__
This is ____6746::PID
This is ____6747::PID
Cube(__3) is _______27.
Square(__4) is _______16.
Done.
Works.
Q.E.D.

import multiprocessing as mp
import os
import sys
import time

def cube( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Cube({0:_>3d}) is {1:_>9d}.".format( num, num*num*num ) )
    sys.stdout.flush()

def square( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Square({0:_>3d}) is {1:_>9d}.".format( num, num*num ) )
    sys.stdout.flush()

if __name__ == "__main__":
    print( "This is {0:_>8d}::__main__".format( os.getpid() ) )
    p1 = mp.Process( target = cube,   args = (3, ) )
    p2 = mp.Process( target = square, args = (4, ) )
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    time.sleep( 1 )

    print( "Done.\nWorks.\nQ.E.D." )

I copied and pasted your exact code. But I still didn't get the output from the called functions using the multiprocessing libraries
Kartikeya Agarwal

所以,
- 我打开了一个新的终端进程,
- 我复制了 conda activate py3 命令和
- 我按 Enter 让它 运行,以使 python3 生态系统上线。
- 我再次启动了解决方案证明 python Whosebug_mp.py
- 我按 Enter 让它 运行
- 我看到它的工作方式与上次完全相同。
- 我怀疑问题出在提供的两次(重新)验证的解决方案证明方面,是吗?
Q.E.D.

(py3) Fri May 29 19:53:58 $ python Whosebug_mp.py
This is ___27202::__main__
This is ___27203::PID
Cube(__3) is _______27.
This is ___27204::PID
Square(__4) is _______16.
Done