C.W.K.
Stream
Lesson 10 of 10 · published

Thread Safety + check_same_thread

~12 min · python, threading, thread-safety

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

곧장 부딪힐 flag

기본값으로 Python sqlite3.Connection 이 만든 thread 에서만 사용 가능. 다른 thread 에서 쓰면 ProgrammingError: SQLite objects created in a thread can only be used in that same thread.

Multi-threaded 앱 처리 3 방법:

  1. Thread 마다 connection — 보통 threading.local(). 단순 + 안전.
  2. Connection pool — 짧은-수명 thread 많은 앱. SQLAlchemy 같은 도구가 알아서.
  3. check_same_thread=False + 본인 lock — 안전 체크 끄고 직접 access serialize. 망치기 쉬움; 정확히 뭐 하는지 알 때만.
Self-reference: 피파 backend 가 thread 대신 aiosqlite (track 7) 사용 — 그게 이걸 통째로 우회, async task 가 정의상 한 thread. Sync threaded 코드는 per-thread connection 패턴이 boring + correct 기본.

Code

Per-thread connection 패턴·python
import sqlite3, threading

_local = threading.local()

def conn() -> sqlite3.Connection:
    if not hasattr(_local, 'c'):
        _local.c = sqlite3.connect('demo.db', timeout=30.0)
        _local.c.execute('PRAGMA journal_mode = WAL')
        _local.c.execute('PRAGMA foreign_keys = ON')
    return _local.c

def worker():
    rows = conn().execute('SELECT count(*) FROM users').fetchone()
    print(threading.current_thread().name, rows)

threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads: t.start()
for t in threads: t.join()

External links

Exercise

16 thread spawn 하는 작은 프로그램, 각 thread 가 SQLite DB 에 read+write mix. Per-thread connection 패턴 구현. WAL 가 reader/writer block 안 함 확인. 그 다음 일부러 한 connection thread 들 사이 share 해서 ProgrammingError 관찰.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.