- 多进程相比多线程,切换时消耗更多的资源和时间, 但是可以使用多核cpu, 多线程虽然消耗少,但是只能使用多核cpu的一个核心,同时使用多线程+多进程提高程序的效率
- 使用多进程的库multiprocessing, 进程库Pool.apply 是阻塞式的, Pool.apply_async是非阻塞式. Pool后面可以跟一个表示进程个数的int类型,一般默认值为CPU核心个数.
- 如果多进程执行时,需要获取执行的结果,可以使用res = Pool.apply_async(target, *args), res.get()获取进程执行结果,
- 如果在类中使用了线程池, 有可能会报错, 需要考虑参数的可序列化.
class A():
def f(self, x):
return x*x
def go(self):
p = Pool(4)
p.map(self.f, range(10))
A.go() # 这样会报错
可以改为:
(1)
class A():
def go(self):
p = Pool(4)
p.map(f, range(10))
def f(x):
return x*x
(2)
class A()
def f(self,x):
return x*x
def go(self):
p = Pool(4)
plist = []
for i in range(10):
process = Process(target=func, args=(self, x)) # 把self,和x作为参数传入
plist.append(process)
p.close() # 关闭pool
p.join()
def func(client, x):
return client.f(x) #client 相当于self
- 多进程通信, 通过Queue或者共享内存
多进程中multiprocessing.Queue是进程安全的, Queue.Queue是线程安全的
共享内存使用的一般是multiprocessing.Manager().Array/list/value/dict等。
参考:https://www.cnblogs.com/lxmhhy/p/6052167.html
另外分布式多进程参考:
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832973658c780d8bfa4c6406f83b2b3097aed5df6000