1. 程式人生 > >Python高階程式設計之資料庫sqlite3(二)

Python高階程式設計之資料庫sqlite3(二)

import logging
import sqlite3
import sys
import threading
import time

logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s (%(threadName)-10s) %(message)s',
    )

db_filename = 'todo.db'
isolation_level = sys.argv[1]

def writer():
    #my_name = threading.currentThread().name
    with sqlite3.connect(db_filename,
            isolation_level = isolation_level) as conn:
        cursor = conn.cursor()
        cursor.execute('update task set priority = priority + 1')
        logging.debug('waiting to synchronize')
        ready.wait() # synchronize threads
        logging.debug('PAUSINE')
        time.sleep(1)
        conn.commit()
        logging.debug('CHANGES COMMITTED')
    return

def reader():
    #my_name = threading.currentThread().name
    with sqlite3.connect(db_filename,
            isolation_level = isolation_level) as conn:
        cursor = conn.cursor()
        logging.debug('waiting to synchronize')
        ready.wait() # synchronize threads
        logging.debug('wait over')
        cursor.execute('select * from task')
        logging.debug('SELECT EXECUTED')
        results = cursor.fetchall()
        logging.debug('result fetched')
    return

if __name__ == '__main__':
    ready = threading.Event()

    threads = [
            threading.Thread(name='Reader 1', target = reader),
            threading.Thread(name='Reader 2', target = reader),
            threading.Thread(name='Writer 1', target = writer),
            threading.Thread(name='Writer 2', target = writer),
            ]

    [ t.start() for t in threads ]

    time.sleep(1)
    logging.debug('setting ready')
    ready.set()

    [ t.join() for t in threads ]
這些執行緒使用threading模組的一個Event完成同步。writer()函式連線資料庫,並完成資料庫修改,不過在事件觸發前並不提交。reader()函式連線資料庫,然後等待查詢資料庫,直到出現同步事件。