这是一个“最佳实践”问题。我正在编写我的第一个多线程代码,我想知道我是否正确地度量了进度。这是我的代码,它可以同时执行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
对于更新的代码示例:
相关问题 更多 >
编程相关推荐