我正在尝试弄清楚psycopg2连接池中SimpleConnectionPool
和ThreadedConnectionPool
之间的区别。
文档中提到:
SimpleConnectionPool
连接只能在单线程应用程序/脚本中使用。
ThreadedConnectionPool
连接可以在多线程应用程序/脚本中安全地使用。
这里的“安全”是什么意思?
我的理解/困惑:
"""
eg1: Simple Connection Pooling example
"""
from psycopg2.pool
from concurrent.futures
def someTask(id):
# CRUD queries to Postgres, that I will be multithreading
print(f"Thread: {id}")
conn = simple_pool.getconn()
# do DB operation
simple_pool = psycopg2.pool.SimpleConnectionPool(10, 15, #DB Info)
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(someTask, range(1,10))
"""
eg2: Threaded Connection Pooling example
"""
from psycopg2.pool
from concurrent.futures
def someTask(id):
# CRUD queries to Postgres, that I will be multithreading
print(f"Thread: {id}")
conn = threaded_pool.getconn()
# do DB operation
threaded_pool = psycopg2.pool.ThreadedConnectionPool(10, 15, #DB Info)
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(someTask, range(1,10))
Q1: 我可能理解有误,但在示例1中,someTask()
函数将被每个线程调用,因此如果它是一个简单的连接池,这将产生错误/不安全(这是什么意思?)。
Q2: 在示例2中,如果示例正确,那么线程安全是什么意思,someTask()
函数将允许从池中获取连接,在示例1中则不会?
Q3: 这两者之间是否有性能差异?
非常感谢您提供更多的资源/文章/文本以更好地理解这个问题。谢谢。