Python多进程脚本运行数小时后崩溃

2 投票
1 回答
1025 浏览
提问于 2025-04-18 18:08

我有一个用Python 3.4写的多进程脚本,运行得还不错,但后来就挂掉了。比如,它能运行大约4个小时,然后我回来看时发现它不再处理任何事情了。

和之前不同的是,现在在后台显示了很多进程。我把它们排序后发现有一堆python3.4的进程。

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
13322 root      20   0  888716 316456   3272 S   0.0  7.8   0:27.09 python3.4
13325 root      20   0  888480 316212   3272 S   0.0  7.8   0:26.54 python3.4
13327 root      20   0  873136 300836   3272 S   0.0  7.4   0:14.83 python3.4
13309 root      20   0  651924 299896   3244 S   0.0  7.4   0:23.38 python3.4
13305 root      20   0  651924 299888   3244 S   0.0  7.4   0:22.17 python3.4
13287 root      20   0 1055324  46800   6268 S   0.0  1.2   0:03.97 python3.4
13414 root      20   0  834128  41344   3264 S   2.3  1.0   0:01.92 python3.4
13415 root      20   0  834128  41344   3264 S   2.0  1.0   0:01.82 python3.4
13416 root      20   0  834128  41344   3264 S   2.0  1.0   0:01.85 python3.4
13417 root      20   0  834128  41344   3264 S   2.0  1.0   0:01.88 python3.4
13418 root      20   0  834128  41344   3264 S   2.3  1.0   0:01.86 python3.4
13419 root      20   0  834128  41344   3264 S   2.7  1.0   0:01.89 python3.4
13420 root      20   0  834128  41344   3264 S   2.0  1.0   0:01.83 python3.4
#About 60 others truncated for brevity
13293 root      20   0  165356  31632   3260 S   0.0  0.8   0:02.46 python3.4
13291 root      20   0  165364  31592   3256 S   0.0  0.8   0:02.37 python3.4
13295 root      20   0  165356  31584   3256 S   0.0  0.8   0:02.44 python3.4

下面是启动处理的代码。我在使用top命令时观察到,每次调用process_score时,已有的python3.4进程仍然存在,并且又新出现了8个进程。最终,我觉得这些进程不断增加,占用了我的资源,导致主脚本“卡住”。

我认为pool.map的一个关键点是它会在退出时终止子进程,我不需要自己去管理和终止它们。那么,我该如何确保子进程被终止呢?在stackoverflow上搜索时,关于使用pool.map时如何终止子进程的信息并不多。

While True
    id_list = get_student_ids()
    if id_list == []:
        break
    else:
        #Multiprocessing starts here:
        num_of_consumers = multiprocessing.cpu_count()
        pool = multiprocessing.Pool(num_of_consumers)
        col_list_insert = pool.map(student_score.process_score, id_list)

1 个回答

1

问题在于你在while循环里不停地创建新的Pool对象。其实应该在while循环外面只创建一次这个池子,然后反复调用pool.map。这样的话,程序运行期间就会一直使用同样的8个进程,而不是每次都重新启动一组新的8个进程。

撰写回答