我正在研究一個多線程的Python腳本,它接收一個文件名列表並將它們放在一個隊列中。大多數時候它可以工作,但是我偶爾會發現它被卡住了,'ps -efL'會顯示兩個線程爲python腳本打開。我用strace跟着它,並且6個線程中有5個返回了,但是一個只是掛在futex上,永遠等待。Python線程偶爾無法返回
下面是有問題的代碼塊。
threads = 6
for fileName in fileNames:
queue.put(fileName)
for i in range(threads):
t = threading.Thread(target=get_backup_list, args=(queue,dbCreds,arguments.verbose,arguments.vault))
activeThreads.append(t)
t.start()
for activeThread in activeThreads:
activeThread.join()
def get_backup_list(queue,dbCreds,verbosity,vault):
backupFiles = []
while True:
if queue.empty() == True:
return
fileName = queue.get()
try:
fileInfo = lookup_file_by_path(fileName,dbCreds,vault)
if not fileInfo:
start = time.time()
attributes = get_attributes(fileName,verbosity)
end = time.time() - start
if verbosity: print("finished in ") + str(end) + (" seconds")
insert_file(attributes,dbCreds,vault)
fileInfo = lookup_file_by_path(fileName,dbCreds,vault)
except Exception, e:
print("error on " + fileName + " " + str(e))
return
def lookup_file_by_path(path,dbCreds,vault):
attributes = {}
conn = mdb.connect(dbCreds['server'] , dbCreds['user'], dbCreds['password'], dbCreds['database'], cursorclass=MySQLdb.cursors.DictCursor);
c = conn.cursor()
c.execute('''SELECT * FROM {} where path = "%s" '''.format(vault) % (path))
data = c.fetchone()
if data:
for key in data.keys():
attributes[key] = data[key]
conn.close
return attributes
我在做一些根本錯誤的事情,導致競爭狀態?或者是有什麼我失蹤了。
感謝, 托馬斯Ç
那麼,'conn.close'缺少一對括號,調用'queue.empty'而不是直接去'get'(可能用'block = False')通常是一個壞主意。 – user2357112