簡體   English   中英

Python線程,測量進度百分比

[英]Python threading, measuring progress percentage

這是一種“最佳做法”問題。 我正在做我的第一個多線程代碼,我想知道自己是否在正確地衡量進度。 這是我的代碼,它一次執行16個文件復制線程,而我正在嘗試創建一個進度條。 這段代碼有效,但是我想知道這是否是“正確”的方法(例如,如果多個線程一次寫入“ copyCount”,該怎么辦?):

import Queue, threading, os
import shutil

fileQueue = Queue.Queue()
destPath = 'destination/folder/here'

class ThreadedCopy:
    totalFiles = 0
    copyCount = 0

    def __init__(self):
        with open("filelist.txt", "r") as txt:
            fileList = txt.read().splitlines()

        if not os.path.exists(destPath):
            os.mkdir(destPath)

        self.totalFiles = len(fileList)

        print str(self.totalFiles) + " files to copy."
        self.threadWorkerCopy(fileList)

    def CopyWorker(self):
        while True:
            fileName = fileQueue.get()
            shutil.copy(fileName, destPath)
            fileQueue.task_done()
            self.copyCount += 1
            percent = (self.copyCount*100)/self.totalFiles
            print str(percent) + " percent copied."

    def threadWorkerCopy(self, fileNameList):
        for i in range(16):
            t = threading.Thread(target=self.CopyWorker)
            t.daemon = True
            t.start()
        for fileName in fileNameList:
            fileQueue.put(fileName)
        fileQueue.join()

ThreadedCopy()

對於其他感興趣的人,我肯定是做錯了。 我找到了這篇奇妙的文章,它用非常簡單的術語解釋了如何使用鎖來處理多個線程: http : //effbot.org/zone/thread-synchronization.htm

對於更新的代碼示例:

import Queue, threading, os
import shutil

fileQueue = Queue.Queue()
destPath = 'destination/folder/here'

class ThreadedCopy:
    totalFiles = 0
    copyCount = 0
    lock = threading.Lock()

    def __init__(self):
        with open("filelist.txt", "r") as txt:
            fileList = txt.read().splitlines()

        if not os.path.exists(destPath):
            os.mkdir(destPath)

        self.totalFiles = len(fileList)

        print str(self.totalFiles) + " files to copy."
        self.threadWorkerCopy(fileList)

    def CopyWorker(self):
        while True:
            fileName = fileQueue.get()
            shutil.copy(fileName, destPath)
            fileQueue.task_done()
            with self.lock:
                self.copyCount += 1
                percent = (self.copyCount*100)/self.totalFiles
                print str(percent) + " percent copied."

    def threadWorkerCopy(self, fileNameList):
        for i in range(16):
            t = threading.Thread(target=self.CopyWorker)
            t.daemon = True
            t.start()
        for fileName in fileNameList:
            fileQueue.put(fileName)
        fileQueue.join()

ThreadedCopy()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM