多线程循环不以Python结尾

2024-04-28 06:57:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写(复制并改编)了一个python程序来做一些备份。它基本上从源位置读取文件,并在目标位置复制或创建硬链接。它是多线程的,这部分工作正常。问题是线程中调用的循环永远不会结束。相关代码如下。我读到它可能是一个线程引发了一个错误并挂起,但不知道如何检查它。程序从文件队列中读取、处理文件,然后应该结束。它读取并处理文件,直到队列为空,然后挂起。有什么建议可以试试看吗?希望我粘贴了足够的代码来提供帮助

print ("beginning backup")
backup(path_to_source, path_to_full, dest_path, backup_type)
print ("Backup finished")

# --- clean full backup
if backup_type == "Full":
    print ("Cleaning up full backup - deleting deleted files")
    clean_backup()
    print ("Backup has been cleaned.  Done")

#--------------------------------------------------
def backup(path_to_source, path_to_full, dest_path, backup_type):
    threadWorkerCopyInc(source_files)
     print ("All Done")   #(never executes)

def threadWorkerCopyInc(fileNameList):
    global num_threads
    #fileQueue = queue.queue()
    for i in range(num_threads):
        t = threading.Thread(target=IncCopyWorker)
        t.daemon = True
        t.start()
        #threads.append(t)
    for fileName in fileNameList:
        fileQueue.put(fileName)
    fileQueue.join()
    #for i in range(len(threads)):
    #    fileQueue.put('None')
    #for t in threads:
    #    t.join()
    print('done with threadworkercopyinc')   #(never executes)


def IncCopyWorker():
    print ('Starting IncCopyWorker. ')   #executes
           
    while True:
        
        filename = fileQueue.get()
        if filename == 'None':
            print("\nFilename is none")  #executes when fileQueue.qsize() = 0
            
        with threadlock: processedfiles +=1
        print ("Files to go: %d  processed files:  %d  newfiles: %d  hardlinks: %d not copied: %d dfsr: %d  " %(fileQueue.qsize(), processedfiles, newfiles, hardlinks, notcopied, dfsr), end = '\r')
       
        is_dfsr = filename.upper().find("DFSR")
       
        if (is_dfsr == -1): 
              #do main processing here
        else:
            with threadlock: dfsr+=1
        fileQueue.task_done()
    print ("done with while true loop")  #never Executes

Tags: 文件topathinsourcefortypewith
1条回答
网友
1楼 · 发布于 2024-04-28 06:57:56

所以我的问题似乎是在try/except块中包含continue语句,以尝试加快执行速度。当有continue或break语句时,循环永远不会结束。当我拿出continue语句时,它按预期的方式完成了。我不知道原因——只是解决办法

相关问题 更多 >