Python:exec与ProcessPoolExecutor

Python:exec与ProcessPoolExecutor,python,python-3.x,parallel-processing,concurrent.futures,Python,Python 3.x,Parallel Processing,Concurrent.futures,mainWork.py from concurrent.futures import ProcessPoolExecutor import os import time def parInnerLoop(item): a = 2+item print(f'A. {a} Processing {os.getpid()} done on {item}\n') exec(open('mainWork.py').read()) print(f'D. {a} Proces

mainWork.py

from concurrent.futures import ProcessPoolExecutor
import os
import time

def parInnerLoop(item):
    a = 2+item
    print(f'A. {a} Processing {os.getpid()} done on {item}\n')
    exec(open('mainWork.py').read())
    print(f'D. {a} Processing {os.getpid()} done on {item}\n')

def main():
    with ProcessPoolExecutor(max_workers=4) as executor:
        for itemNo in range(10):
            executor.submit(parInnerLoop, itemNo)
    print('done')

if __name__ == '__main__':
    main()
错误:

print(f'B. {a} Processing {os.getpid()} done on {item}\n')
a = 12
print(f'C. {a} Processing {os.getpid()} done on {item}\n')
问题:

  • 错误出现在程序的末尾
  • 我想将
    mainWork.py
    的所有代码作为
    parInnerLoop
    的一部分执行,这样
    a
    的值的变化应该反映在
    parInnerLoop
    以及
    mainWork.py
    中,反之亦然。我得到如下输出。
    a
    的值在打印以
    D开始的位置不会改变…
    ,我希望它是12
  • 项目
    0

    Error in atexit._run_exitfuncs:
    Traceback (most recent call last):
      File "D:\Program Files\Python\Python37\Lib\concurrent\futures\process.py", line 101, in _python_exit
        thread_wakeup.wakeup()
      File "D:\Program Files\Python\Python37\Lib\concurrent\futures\process.py", line 89, in wakeup
        self._writer.send_bytes(b"")
      File "D:\Program Files\Python\Python37\Lib\multiprocessing\connection.py", line 183, in send_bytes
        self._check_closed()
      File "D:\Program Files\Python\Python37\Lib\multiprocessing\connection.py", line 136, in _check_closed
        raise OSError("handle is closed")
    OSError: handle is closed
    
    发生了什么事?请帮忙

    我最终想要实现的是:以不同的设置并行运行相同的代码,而不相互干扰

    额外:

  • 我测试了ProcessPoolExecutor是否正常工作,如图所示
  • 我使用以下代码测试了exec(open('run.py').read())是否按预期工作:
  • main.py

    A. 2 Processing 19784 done on 0
    B. 2 Processing 19784 done on 0
    C. 12 Processing 19784 done on 0
    D. 2 Processing 19784 done on 0
    
    run.py

    def myFun():
        a = 1
        b = 2
        print(a)
        exec(open('run.py').read())
        #execfile("run.py")
        print(a)
        print(b)
        print(c)
    
    def main():
        myFun()
    
    if __name__ == '__main__':
        main()
    
    输出

    a = a+5
    b = 10
    c = 15
    

    不是一个完整的答案,但它似乎与

    谢谢你的报道!经过快速调查,问题似乎是因为concurrent.futures模块最近发生了更改。简而言之,它们维护一个对某些服务线程(名为“QueueManagerThread”)的弱引用字典,并在退出Python进程时尝试关闭字典中的任何线程。字典通常为空,但如果存在对线程的引用,则可能会导致尝试关闭不活动的线程。在这种情况下,将引发原始异常


    我在Linux上遇到了与3.7.6相同的问题。这似乎是一个开放的市场bug@nodakai,谢谢您的确认。@nokada,我在Windows上使用Python 3.7.8时遇到了同样的问题。看起来像,但尚未修复。请更新到python 3.9+以解决此问题
    1
    6
    10
    15