import threading
import time
import sqlite3
event = threading.Event()
conn = sqlite3.connect('test.s3db', check_same_thread=False)
cur = conn.cursor()
lock = threading.Lock()
def foo():
global count
while not event.is_set(): # 返回event的状态值,同isSet
count += 1
if count % 10000 != 0: # 一万次insert才commit,提高效率
lock.acquire(True) # 加锁来避免数据成功写入
try:
cur.execute('''insert into test(id,name) values(?,?)''', (1, 'good boy'))
except:
print(count)
lock.release()
else:
conn.commit()
print("connect to server")
for i in range(5): # 5个子线程同时等待
t = threading.Thread(target=foo, args=())
t.start()
print("start server successful")
time.sleep(10)
event.set() # 设置标志位为True,event.clear()是回复event的状态值为False
time.sleep(1)
cur.close()
conn.close()
python thread event sqlite
最新推荐文章于 2022-09-25 14:17:56 发布