问题描述
根据 psycopg2
文档:
跟随链接文档指向:
但是看来打开插座的分叉过程固有的问题.那么psycopg2
在打开连接时发出分叉警告的原因是什么?
But it seems there's no inherent problem with forking processes with open sockets. So what's the reason for psycopg2
's warning against forking when connections are open?
我提出这个问题的原因是,我看到了一种(大概成功的)多处理方法,它在分叉之前就打开了连接.
The reason for my question is that I saw a (presumably successful) multiprocessing approach that opened a connection right before forking.
在某些限制下分叉打开的连接也许是安全的(例如,实际上只有一个进程使用该连接等)?
Perhaps it is safe to fork open connections under some restrictions (e.g., only one process actually ever uses the connection, etc.)?
推荐答案
您的猜测基本上是正确的:只要您不尝试在多个分支中使用它,在fork之前打开连接就没有问题.过程.
Your surmise is basically correct: there is no issue with a connection being opened before a fork as long as you don't attempt to use it in more than one process.
修改:
通常,应该在使用它的过程中创建一个连接.在引用的答案中,在分叉之前先在父级中创建一个连接,然后在子级中使用该连接.这确实可以正常工作,但是每个子连接"也都在父级中保持打开状态,这充其量是在浪费资源和潜在错误的原因.
Edit:
As a general practice, one should prefer creating a connection within the process that is using it. In the answer cited, a connection was being created in the parent before forking, then used in the child. This does work fine, but leaves each "child connection" open in the parent as well, which is at best a waste of resources and also a potential cause of bugs.
这篇关于跨进程共享psycopg2/libpq连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!