在升级程序到 python3.9 后,异步非阻塞的子进程起不来了,实际代码在python3.6 版是可以运行的 :
程序逻辑及相关使用方式大概是这样的
def job(x):
return x * x
if name == “main”:
pool multiprocessing.Pool()
res = [pool.apply_async(target=job, (i,)) for i in range(3)]
print [r.get() for r in res]
更接近的代码是这样的:
#第一个 python.py
import time, os
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
def output(self):
print('Run task %s (%s)...' % (self, os.getpid()))
i = 0
while True:
time.sleep(1)
self.print_score()
time.sleep(2)
print("grade:", self.get_grade())
i += 1
在另外的文件进行多进程
from multiprocessing import Pool
import os, time
from job import Student
def facade_it(ts, name):
p = Pool(4)
for i in range(5):
stu = Student.Student(name[i], (i + 15) * ts)
p.apply_async(stu.output)
print("up apply_async")
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
if __name__ == '__main__':
l = ['Allen', "Belle", "Carl", "David", "Even"]
ts = 5
facade_it(ts, l)
示例中的 student 只是小学生,实际项目中的是个大学生,仅此而已。
具体表现
能以func=* 的方式运行起来,不是变成单线程了,一个子线程(假的)会block 后面的子线程
能启动多个线程,线程中调用 示例函数不成功,立即结束了 ( CAO~~~!Cao~~~ CI !AO !)
网上一般给以下几种情况:
1. 用Pool的apply_async(异步非阻塞)的时候传入实例函数会出错,或者说是子进程被跳过似的感觉(python2.7)
javascript:void(0)
很少人用python2 了 ,不过有解决方案
https://stackoverflow.com/questions/19924104/python-multiprocessing-handling-child-errors-in-parent
2. 在pool.apply_async(target, args)
中的args参数元祖中,只有一个参数,但是参数后面没有加逗号
这是基础知识问题。另外,这个是子进程不抛出错误(Python 的锅????)
3. 使用了进程中的event()函数。 老版本的方式,不建议用
4. 用Manager
来管理multiprocessing.Queue
,这样线程池中的子线程才会运行
我的问题不在以上范围中,也不是因为引入其他模块的类文件的原因(一开始以为是这个很欣喜)
,对于一个Python 菜鸡,只能放飞自我了
可能有以下解决方式:
1. pathos模块 试试
https://zhuanlan.zhihu.com/p/46378282
2. Coroutine
https://www.jianshu.com/p/bda2d6059723