SQLAlchemy自动加载线程安全吗?

peo*_*eon 5 python sqlalchemy

自动加载线程安全吗?我找不到与此有关的任何文档。通过以下代码,无法在大约前20毫秒内成功加载表(无异常,没有警告或更高级别的日志,但table.columns是一个空列表)。

from sqlalchemy import *
import logging
import threading
import time

logging.basicConfig(level = logging.INFO, format = '%(asctime)s:%(message)s', filename = "autoload_test.log")
logging.getLogger("sqlalchemy").setLevel(logging.DEBUG)
engine = create_engine("postgresql://madk@localhost/mydb", echo = False)
metadata = MetaData(bind=engine)

lock = threading.Lock()
def load_table():
    while True:
        try:
            table = Table('mytbl', metadata, autoload=True, autoload_with=engine)
            logging.info("size of columns:[%s]", len(table.columns))
        except:
            logging.warn("error occured", exc_info = True)

for i in range(5):
    t = threading.Thread(target = load_table)
    t.daemon = False
    t.start()

time.sleep(4)
Run Code Online (Sandbox Code Playgroud)
  1. 1个线程:成功加载
  2. 具有多线程且没有锁定保护:所有线程在开始的20ms失败(空列),然后所有线程正常工作
  3. 多线程带锁保护:添加线程成功加载