Created
September 25, 2023 01:21
-
-
Save mdukat/988d56e445674b9cab8f1f07ced52f6c to your computer and use it in GitHub Desktop.
Multithreading sqlite3 INSERT with Lock() example I made at 3am
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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