pk1*_*k10 6 python psycopg2 python-multithreading python-3.x
我试图找出 psycopg2 连接池之间的SimpleConnectionPool区别ThreadedConnectionPool。
该文档说:
SimpleConnectionPool连接只能在单线程应用程序/脚本内使用。
ThreadedConnectionPool连接可以在多线程应用程序/脚本中安全地使用。
这里是什么safely意思?
我的理解/困惑:
"""
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))
Run Code Online (Sandbox Code Playgroud)
"""
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))
Run Code Online (Sandbox Code Playgroud)
Q1:我可能理解错误,但在eg1中,该someTask()函数将被每个线程调用,所以如果它是简单的连接池,这将出错/将是不安全的(这是什么意思?)。
Q2:在eg2中,如果示例没问题,那么THREAD SAFE意味着什么,someTask()函数将被允许从池中获取连接,而在eg1中则不允许?
Q3:两者的性能有区别吗?
非常感谢我可以阅读以更好地理解这一点的任何其他资源/文章/文本。谢谢。