所以,我正在尝试编写一个应用程序,它使用django作为其ORM,因为它需要在后台执行一些处理操作并提供易于使用的前端界面。它的核心功能将是处理存储在数据库中的数据,使用高CPU进程(基本上是蒙特卡罗模拟),我想要实现多进程处理,具体使用Pool(我获取了4个进程)。基本上,我的代码像这样运行,父进程约有20个子进程:
assorted import statements to get the django environment in the script
from multiprocessing import Pool
from random import random
from time import sleep
def test(child):
x=[]
print child.id
for i in range(100):
print child.id, i
x.append(child.parent.id) #just to hit the DB
return x
if __name__ == '__main__':
parent = Parent.objects.get(id=1)
pool = Pool()
results = []
results = pool.map(test,parent.children.all())
pool.close()
pool.join()
print results
使用这样的代码,我会间歇性地遇到DatabaseError
或PicklingError
。前者通常是"数据库格式错误"或"与MySQL服务器的连接丢失"等形式,后者通常是"无法对模型进行pickle.DoesNotExist"。它们是随机发生的,会出现在任何进程中,并且当然数据库本身没有问题。如果我设置pool = Pool(proccesses=1)
,那么程序就可以运行,在单个线程中完美运行。我还加入了各种打印语句来确保大部分情况下实际上正在运行。
我还一直在将test
更改为:
def test(child):
x=[]
s= random()
sleep(random())
for i in range(100):
x.append(child.parent.id)
return x
这只会使每次迭代在运行前暂停不到一秒钟,这样一切都没问题。如果我将随机间隔减少到约500毫秒,它就开始出问题了。所以,很可能是并发问题,对吧?但只有4个进程在运行。我的问题是,如何在不提前大量转储数据的情况下解决这个问题?我已经使用了SQLite和MySQL进行了测试,但两者都无法解决这个问题。
multiprocessing.Lock
来避免所有对数据库的竞争条件呢? - Bakuriu