Documentation says that connection pool also is not designed for multithreading:
It’s critical that when using a connection pool, and by extension when using an Engine created via create_engine(), that the pooled connections are not shared to a forked process. TCP connections are represented as file descriptors, which usually work across process boundaries, meaning this will cause concurrent access to the file descriptor on behalf of two or more entirely independent Python interpreter states.
As i understand this, if i create connection pool:
self.engine = create_engine('postgresql://{user}:{password}@{host}:{port}/{db}'.format(
user=Configuration().get(section='repository', option='user'),
password=Configuration().get(section='repository', option='password'),
host=Configuration().get(section='repository', option='host'),
port=Configuration().get(section='repository', option='port'),
db=Configuration().get(section='repository', option='database')
), echo=False, pool_size=3)
self.session = sessionmaker(self.engine, expire_on_commit=False)
and then call self.session()
in different threads i will have 3 different connections which are used in N different threads.
Does it mean that only 3 concurrent thread will do some work while others will wait until one or more thread will call session.close()
? Or there is a chance that >2 threads will use the same connection simultaneously?
Is NullPool safer (because each new session is a new connection) or no?
self.engine = create_engine('postgresql://{user}:{password}@{host}:{port}/{db}'.format(
user=Configuration().get(section='repository', option='user'),
password=Configuration().get(section='repository', option='password'),
host=Configuration().get(section='repository', option='host'),
port=Configuration().get(section='repository', option='port'),
db=Configuration().get(section='repository', option='database')
), echo=False, poolclass=NullPool)
The general question: is it ok to use the same connection pool in such case:
engine = create_engine('connection_string', echo=False, pool_size=3)
Session = sessionmaker(engine)
def some_function():
session = Session()
...
pool = Pool(processes=10)
pool.map(some_function)
pool.close()
pool.join()