多进程和mongo的配合使用

这篇文章主要是讲在多线程下使用mongo数据库的一个报错,算是一个警告,如下:

/usr/lib64/python2.6/site-packages/pymongo/topology.py:75: UserWarning: MongoClient opened before fork. Create MongoClient with connect=False, or create client after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#using-pymongo-with-multiprocessing> "MongoClient opened before fork. Create MongoClient "

提示是mongo连接在fork之前就被创建了,希望你加connect=False参数或者在fork以后再建立连接

打开提示的网站,会发现提示:

  Instances of MongoClient copied from the parent process have a high probability of deadlock in the child process due to inherent incompatibilities between fork(), threads, and locks. PyMongo will attempt to issue a warning if there is a chance of this deadlock occurring.

  由于fork(),线程和锁之间固有的不兼容性,从父进程复制的MongoClient实例在子进程中具有很高的死锁概率如果有可能发生此死锁,PyMongo将尝试发出警告。

解决办法就是:

1.加上connect=False参数

  如果pymongo版本比较老的话是不支持connect=False这个参数的,升级一下就好了

2.把初始化数据库连接的代码放到fork以后,就是在进程里面需要的时候再初始化。

 

原文地址:https://www.cnblogs.com/mswei/p/9683367.html