I am trying to figure out the difference between SimpleConnectionPool
and ThreadedConnectionPool
in psycopg2 connection pool.
The doc says:
SimpleConnectionPool
connections can only be used inside a single threaded application/script.
ThreadedConnectionPool
connections can be safely used inside multi-threaded app/script.
What does safely
mean here?
My understanding/confusion:
"""
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: I may be understanding this incorrectly, but in eg1 the someTask()
function will be called per thread, so if its simple connection pool, this will error out/will be UNSAFE (what does this mean?).
Q2: And in eg2, if the example is fine, what THREAD SAFE means, the someTask()
function will be allowed to get a connection out of the pool and in eg1 it won't?
Q3: Is there any performance difference between the two?
Any additional resources/articles/texts I can read to understand this better, is much appreciated. Thank you.