我想在这里我需要一些建议。下面是我的代码:

from multiprocessing import Pool
import time
import sys

def testing(number):
    count = 0
    while True:
        print('Count: {}'.format(count))
        count += 1

        if count > number:
            print('Exiting...')
            sys.exit()
        else:
            print('Looping Over')
            time.sleep(1)

if __name__ == '__main__':

    with Pool(2) as p:
        p.map(testing, [3, 2])

预期结果:

一旦所有子线程都退出,程序(主线程)应退出。

实际结果:
$ python3 test_exit.py
Count: 0
Looping Over
Count: 0
Looping Over
Count: 1
Looping Over
Count: 1
Looping Over
Count: 2
Looping Over
Count: 2
Exiting...   <<< Exited 1st thread.
Count: 3
Exiting...   <<< Exited 2nd thread.
....and it stays here as if stuck or something. It never gives control back to Shell.

预期结果:
$ python3 test_exit.py
Count: 0
Looping Over
Count: 0
Looping Over
Count: 1
Looping Over
Count: 1
Looping Over
Count: 2
Looping Over
Count: 2
Exiting...
Count: 3
Exiting...
$   <<< Note: I am expecting to be dropped back to Shell prompt

问题:

就池/映射的使用而言,我的方法有什么问题吗?

最佳答案

一旦所有子线程都退出,程序(主线程)应退出。

  • 通过终止其目标函数testing()(通过关键循环中的break语句完成)来完成一个过程
    进程池完成后,
  • 退出主线程/程序。

  • from multiprocessing import Pool, current_process
    import time
    import sys
    
    def testing(number):
        count = 0
        while True:
            print('Count: {}'.format(count))
            count += 1
    
            if count > number:
                print('Exiting...', current_process().name)
                break
            else:
                print('Looping Over')
                time.sleep(1)
    
    if __name__ == '__main__':
    
        with Pool(2) as p:
            p.map(testing, [3, 2])
        sys.exit()
    

    输出:
    Count: 0
    Looping Over
    Count: 0
    Looping Over
    Count: 1
    Looping Over
    Count: 1
    Looping Over
    Count: 2
    Looping Over
    Count: 2
    Exiting... ForkPoolWorker-2
    Count: 3
    Exiting... ForkPoolWorker-1
    $
    

    关于python - 多重处理:池和 map 以及sys.exit(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56698824/

    10-10 02:51