Python线程,测量进度百分比

时间:2017-08-05 22:30:22

标签: python multithreading

这是一种“最佳实践”问题。我正在做我的第一个多线程代码,我想知道我是否正在测量进度。这是我的代码,它同时执行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()

1 个答案:

答案 0 :(得分:0)

对于其他任何感兴趣的人我都是这样做的。我找到了这篇很棒的文章,用非常简单的术语解释了如何使用锁来解决多个线程: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()