Python-使用线程或队列对调用函数的循环进行迭代

2024-09-30 03:24:59 发布

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

我对python相当陌生,正在编写一个脚本,允许用户将其他程序中的点云数据引入autodeskmaya。我的脚本运行良好,但我要做的是使它更快。我有一个for循环,它遍历一个编号文件的列表。一、 e.datafile001.txt、datafile002.txt等。我想知道的是,是否有一种方法可以让它一次多做一个,可能使用线程或队列?下面是我一直在研究的代码:

     def threadedFuntion(args):
         if len(sourceFiles) > 3:
             for count, item in enumerate(sourceFiles):
                     t1=Thread(target=convertPcToPdc,args=(sourceFiles[filenumber1], particlesName, startframe, endframe, pdcIncrements, outputDirectory, variableFolder, acceptableArrayforms, dataType))
                     t1.start()
                     t2=Thread(target=convertPcToPdc,args=(sourceFiles[filenumber2], particlesName, startframe, endframe, pdcIncrements, outputDirectory, variableFolder, acceptableArrayforms, dataType))
                     t2.start()
                     t3=Thread(target=convertPcToPdc,args=(sourceFiles[filenumber3], particlesName, startframe, endframe, pdcIncrements, outputDirectory, variableFolder, acceptableArrayforms, dataType))
                     t3.start()
                     t4=Thread(target=convertPcToPdc,args=(sourceFiles[filenumber4], particlesName, startframe, endframe, pdcIncrements, outputDirectory, variableFolder, acceptableArrayforms, dataType))
                     t4.start()

这显然不起作用的原因有很多,首先它只会创建4个线程,我想能够给一个或多或少的选择。第二个错误是因为它试图重用一个线程?就像我说的,我对python还不太熟悉,我已经在这里读了好几篇文章,但是没有一篇能够很好地发挥作用。我想队列可能是我需要的东西,但是我不能很好地理解它,我尝试了condition语句和join语句,但是再一次无法得到我想要的东西。在

我想更具体地说,我想实现的是函数是读取文本文件,检索坐标,然后将它们导出为二进制文件供maya读取。其中一个文本文件通常有500-1000万个x,y,z坐标,这需要相当长的时间。在一台相当糟糕的计算机上完成一个文件大约需要30分钟-1个小时,任务管理器说python只使用了12%的处理器和1%左右的ram,所以如果我可以一次完成多个这样的任务,那么完成100个或更多个文件的速度会快得多。我不认为对for循环进行多线程/排队并不困难,但我已经迷失了方向,尝试了大约一周的失败解决方案。在

谢谢你们所有的帮助,我真的很感激,我认为这个网站是惊人的。这是我的第一篇文章,但我觉得我已经完全学会了python。在


Tags: 文件targetargsthreadstartdatatypeoutputdirectorysourcefiles
2条回答

子类线程。线程并将您的工作函数作为run()的一部分放入该类中。在

import threading
import time
import random

class Worker(threading.Thread):
    def __init__(self, srcfile, printlock,**kwargs):
        super(Worker,self).__init__(**kwargs)
        self.srcfile = srcfile
        self.lock = printlock # so threads don't step on each other's prints

    def run(self):
        with self.lock:
            print("starting %s on %s" % (self.ident,self.srcfile))
        # do whatever you need to, return when done
        # example, sleep for a random interval up to 10 seconds
        time.sleep(random.random()*10)
        with self.lock:
            print("%s done" % self.ident)


def threadme(srcfiles):
    printlock = threading.Lock()
    threadpool = []
    for file in srcfiles:
        threadpool.append(Worker(file,printlock))

    for thr in threadpool:
        thr.start()

    # this loop will block until all threads are done
    # (however it won't necessarily first join those that are done first)
    for thr in threadpool:
        thr.join()

    print("all threads are done")

if __name__ == "__main__":
    threadme(["abc","def","ghi"])

根据要求,要限制线程数,请使用以下命令:

^{pr2}$

注意,这实际上将反向处理源代码(由于list pop())。如果您要求按顺序执行,请在某处反转列表,或使用deque和popleft()。在

为此,我建议使用mrjob。在

Mr-Job是map reduce的python实现。在

以下是mr作业代码,用于对大量文本文件进行多线程字数统计:

from mrjob.job import MRJob

class MRWordCounter(MRJob):
    def get_words(self, key, line):
        for word in line.split():
            yield word, 1

    def sum_words(self, word, occurrences):
        yield word, sum(occurrences)

    def steps(self):
        return [self.mr(self.get_words, self.sum_words),]

if __name__ == '__main__':
    MRWordCounter.run()

这段代码并行映射所有文件(计算每个文件的字数),然后将各种计数减少到一个单独的总字数。在

相关问题 更多 >

    热门问题