我写了一个这样的 python 程序,应该在多线程模式下运行:
def Func(host,cursor,db):
cursor.execute('''SELECT If_index, Username, Version, Community, Ip_traff FROM HOST WHERE
Hostname = ?''',(host,))
#do something
#--- Main ---
db = sqlite3.connect(os.getcwd()+'\HOST', check_same_thread = False) #opendatabase
cursor = db.cursor() #generate a cursor
for ii in range(len(host)): #host is a list of ipaddress
#for each host i want generate a thread
thr = threading.Thread(target = Func, args=(host[ii],cursor,db)
thr.start()
我收到 sqlite3.ProgrammingError:不允许递归使用游标。在这种情况下,我如何管理 sqlite3 的递归游标? 多谢 保罗
最佳答案
嗯,问题是 sqlite3 模块不喜欢多线程情况,您可以在 sqlite3 模块的文档中看到这一点
...the Python module disallows sharing connections and cursors between threads[1]
我要做的是在 Func 函数中使用某种同步,例如 threading.Lock[2]。您的 Func 将如下所示:
# Define the lock globally
lock = threading.Lock()
def Func(host,cursor,db):
try:
lock.acquire(True)
res = cursor.execute('''...''',(host,))
# do something
finally:
lock.release()
前面的代码会同步cursor.execute的执行,只让一个线程拿锁,其他线程会一直等到它被释放,当有锁的线程完成后,它会释放锁供其他线程使用拿去吧。
这应该可以解决问题。
[1] https://docs.python.org/2/library/sqlite3.html#multithreading
[2] https://docs.python.org/2/library/threading.html?highlight=threading#rlock-objects
关于Python 和 sqlite3.ProgrammingError : Recursive use of cursors not allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26629080/