多处理:池和映射以及 sys.exit()

sla*_*fer 5 python multiprocessing

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

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])
Run Code Online (Sandbox Code Playgroud)

预期结果:

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

实际结果:

$ 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.
Run Code Online (Sandbox Code Playgroud)

预期结果:

$ 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
Run Code Online (Sandbox Code Playgroud)

题:

在池/地图使用方面,我的方法有什么问题吗?

Rom*_*est 3

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

  • 通过终止其目标函数来完成一个进程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()
Run Code Online (Sandbox Code Playgroud)

输出:

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
$
Run Code Online (Sandbox Code Playgroud)