首页 > 解决方案 > SimpleConnectionPool vs ThreadedConnectionPool:线程安全意味着什么?

问题描述

我试图找出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))


"""
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:我可能理解不正确,但在 eg1 中,someTask()函数将按线程调用,所以如果它是简单的连接池,这将出错/将是UNSAFE(这是什么意思?)。

Q2:在 eg2 中,如果示例没问题, THREAD SAFE是什么意思,该someTask()函数将被允许从池中获取连接,而在 eg1 中则不会?

Q3:两者在性能上有区别吗?

非常感谢我可以阅读以更好地理解这一点的任何其他资源/文章/文本。谢谢你。

标签: pythonpython-3.xpsycopg2python-multithreading

解决方案


根据 的文档SimpleConnectionPool它被定义为:

无法跨不同线程共享的连接池

这证实了你在第一个问题中所说的话。即使它运行时没有错误,SimpleConnectionPool在多个线程中同时使用可能会由于线程之间的竞争条件而导致未定义的行为/错误结果。

至于您的第二个问题,线程安全意味着一个对象可以由多个线程同时使用,而无需处理竞争条件。如果您遵循. ThreadedConnectionPool使用锁来确保没有连接被两个线程同时共享。

我无法评论两者之间的性能差异,因为它们有不同的用例。


推荐阅读