pao*_*ssi 5 python sqlite multithreading cursor
我写了一个这样的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()
Run Code Online (Sandbox Code Playgroud)
我收到sqlite3.ProgrammingError:不允许递归使用游标。在这种情况下,如何管理sqlite3的递归游标?非常感谢Paolo
小智 5
好吧,事实是sqlite3模块不喜欢多线程情况,您可以在sqlite3模块的文档中看到
... Python模块不允许在线程之间共享连接和游标[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()
Run Code Online (Sandbox Code Playgroud)
前面的代码将同步游标的执行。通过仅让一个线程获取锁来执行execute,其他线程将等待直到其被释放为止,当带有锁的线程完成时,它将释放锁以供其他线程获取。
那应该解决问题。
[1] https://docs.python.org/2/library/sqlite3.html#multithreading
[2] https://docs.python.org/2/library/threading.html?highlight=threading#rlock-objects
| 归档时间: |
|
| 查看次数: |
3953 次 |
| 最近记录: |