python / python/cpython

SQLite3 threadsafety property should return 2 for serialized

未關閉
#123,873 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

topic-sqlite3 type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

If the underlying SQLite library sqlite3_threadsafe() function returns 1 (i.e. SERIALIZED) the sqlite3.threadsafety property returns 3, meaning that cursor can be shared between threads.
The sqlite3 module cannot really share cursors between threads, though.
Sometimes it ends up in check_cursor_locked(), more often it segfaults.
Given the dubious value of sharing cursors between threads, introducing the locks needed to support level 3 seems unnecessary.
Until #118172 is fixed, sqlite3.threadsafety should return 1 (share module only).

Reproducible with a test program similar to the one in #118172

import sqlite3
import threading

numthreads=10
KB = None
threadcursor = None
print(f"sqlite3.threadsafety: {sqlite3.threadsafety}")

def execute_query():
    threadcursor.execute("SELECT * FROM test_table")
    result = threadcursor.fetchall()
    assert result == [(1, 'test1'), (2, 'test2'), (3, 'test3')], str(result)
    return result

def run_threads():
    global threadcursor
    threadcursor = KB.cursor()
    threads = []
    for i in range(numthreads + 1):
        thread = threading.Thread(target=execute_query)
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

def test_multithreading():
    global KB
 
    KB = sqlite3.connect(
        "example.db", check_same_thread=False
    )
    cursor = KB.cursor()

    cursor.execute(
        """CREATE TABLE IF NOT EXISTS test_table (id INTEGER PRIMARY KEY, value TEXT)"""
    )
    KB.commit()

    cursor.execute("""DELETE FROM test_table""")
    KB.commit()

    cursor.execute("""INSERT INTO test_table (value) VALUES ('test1')""")
    cursor.execute("""INSERT INTO test_table (value) VALUES ('test2')""")
    cursor.execute("""INSERT INTO test_table (value) VALUES ('test3')""")
    KB.commit()

    run_threads()
    KB.close()


if __name__ == "__main__":
    test_multithreading()
CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-124316

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從報告中描述的 sqlite3.threadsafety 屬性和 sqlite3_threadsafe() 對應開始,然後執行提供的多執行緒重現程式。審查連結的 PR gh-124316 及其測試;當回報的 threadsafety 值和游標共享行為符合已達成的解決方案,且不會出現所示範的失敗時,即視為完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
databases
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
20/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。