import threading import sqlite3 # 创建互斥锁 lock = threading.Lock() # 连接到数据库 conn = sqlite3.connect("database.db") def task(): # 获取锁 lock.acquire() try: # 执行数据库操作 cursor = conn.cursor() cursor.execute("SELECT * FROM table") rows = cursor.fetchall() # 其他数据库操作... finally: # 释放锁 lock.release() # 创建多个任务线程 threads = [] for _ in range(5): t = threading.Thread(target=task) threads.append(t) # 启动任务线程 for t in threads: t.start() # 等待所有任务线程完成 for t in threads: t.join() # 关闭数据库连接 conn.close()