Skip to content

Instantly share code, notes, and snippets.

@mdukat
Created September 25, 2023 01:21
Show Gist options
  • Save mdukat/988d56e445674b9cab8f1f07ced52f6c to your computer and use it in GitHub Desktop.
Save mdukat/988d56e445674b9cab8f1f07ced52f6c to your computer and use it in GitHub Desktop.
Multithreading sqlite3 INSERT with Lock() example I made at 3am
import threading
import sqlite3
def threadfunc(name, con, lock):
print(name)
with lock:
with con:
con.execute("INSERT INTO test VALUES (?)", (name,))
if __name__ == "__main__":
lock = threading.Lock()
threads = []
con = sqlite3.connect("test.db", check_same_thread=False)
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS test(a INTEGER)")
for i in range(0,50):
threads.append(threading.Thread(target=threadfunc, args=(i,con,lock)))
threads[-1].start()
for t in threads:
t.join()
con.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment