MongoReplicaSetClient docs明确指出,您不能fork
进程并在两个进程中使用MongoReplicaSetClient
。
问题:是否保证MongoClient会在流程 fork 后工作吗?还是在每个进程中独立启动与数据库的单独连接更好?
据我所知,文件描述符cannot be safely used在进程 fork 之后更进一步,因为两个进程共享相同的文件描述结构。然而,这些不是文件,而是网络连接,包裹在一些 python 类中;所以我基本上不知道类似的逻辑是否适用于这里,MongoClient
,或者由于某种原因保证它实际工作正常。
我也不明白,如果任何子进程先于其他进程退出,网络连接是否会关闭(简单的写法表明它不会,但为什么总是这样?)。
最佳答案
MongoClient 3.2 可以在 fork() 之后工作,但仅限于某些平台。这是文档的一个片段:http://api.mongodb.org/python/current/faq.html#using-pymongo-with-multiprocessing
There are a few things to be aware of when using multiprocessing with PyMongo. On certain platforms (defined here) MongoClient MUST be initialized with connect=False if a MongoClient used in a child process is initialized before forking. If connect cannot be False, then MongoClient must be initialized AFTER forking.
This is because CPython must acquire a lock before calling getaddrinfo(). A deadlock will occur if the MongoClient‘s parent process forks (on the main thread) while its monitor thread is in the getaddrinfo() system call.
PyMongo will issue a warning if there is a chance of this deadlock occurring.
关于unix - os.fork 之后的 pymongo.MongoClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25641305/