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

2024-04-03

我对 python 相当陌生,正在制作一个脚本,允许将其他程序的点云数据引入 Autodesk Maya。我的脚本运行良好,但我想做的是让它更快。我有一个 for 循环,它遍历编号文件的列表。 IE。 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 很陌生,而且有点不知所措,我已经阅读了这里的几篇文章,但无法让其中一篇正常工作。我认为队列可能是我需要的东西,但无法完全弄清楚,我尝试了条件语句和连接语句,但再次无法得到我想要的。

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

谢谢大家的帮助,我真的很感激,并认为这个网站很棒。这是我的第一篇文章,但我觉得读到这里我已经完全学会了Python。


子类 threading.Thread 并将工作函数作为 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"])

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

def threadme(infiles,threadlimit=None,timeout=0.01):
    assert threadlimit is None or threadlimit > 0, \
           "need at least one thread";
    printlock = threading.Lock()
    srcfiles = list(infiles)
    threadpool = []

    # keep going while work to do or being done
    while srcfiles or threadpool:

        # while there's room, remove source files
        # and add to the pool
        while srcfiles and \
           (threadlimit is None \
            or len(threadpool) < threadlimit):
            file = srcfiles.pop()
            wrkr = Worker(file,printlock)
            wrkr.start()
            threadpool.append(wrkr)

        # remove completed threads from the pool
        for thr in threadpool:
            thr.join(timeout=timeout)
            if not thr.is_alive():
                threadpool.remove(thr)

    print("all threads are done")

if __name__ == "__main__":
    for lim in (1,2,3,4):
        print("--- Running with thread limit %i ---" % lim)
        threadme(("abc","def","ghi"),threadlimit=lim)

请注意,这实际上会反向处理源(由于列表 pop())。如果您要求它们按顺序完成,请在某处反转列表,或使用双端队列和 popleft()。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python - 使用线程或队列迭代调用函数的 for 循环 的相关文章

  • 如何在 QTableView 标题中单击鼠标右键单击上下文菜单?

    下面的示例代码 很大程度上受到here http www saltycrane com blog 2007 12 pyqt 43 qtableview qabstracttablemodel 有一个右键单击上下文菜单 当用户单击表中的单元格
  • 区分大小写的实体识别

    我的关键字全部以小写形式存储 例如 折扣耐克鞋 我正在尝试对其执行实体提取 我遇到的问题是 spaCy 在 NER 方面似乎区分大小写 请注意 我不认为这是 spaCy 特有的 当我跑步时 doc nlp u i love nike sho
  • sy.sympify(str(表达式)) 不等于表达式

    据我了解 str将 SymPy 表达式转换为字符串并sympify将字符串转换为 SymPy 表达式 因此 我希望以下内容成立 对于合理的表达 gt gt gt sy sympify str expr expr True 我尝试过这个 确实
  • 如何使用 python、openCV 计算图像中的行数

    我想数纸张 所以我正在考虑使用线条检测 我尝试过一些方法 例如Canny HoughLines and FLD 但我只得到处理过的照片 我不知道如何计算 有一些小线段就是我们想要的线 我用过len lines or len contours
  • Python 中 time.sleep 和多线程的问题

    我对 python 中的 time sleep 函数有疑问 我正在运行一个脚本 需要等待另一个程序生成 txt 文件 虽然 这是一台非常旧的机器 所以当我休眠 python 脚本时 我遇到了其他程序不生成文件的问题 除了使用 time sl
  • 如何在动态执行的代码字符串中使用inspect.getsource?

    如果我在文件中有这段代码 import inspect def sample p1 print p1 return 1 print inspect getsource sample 当我运行脚本时 它按预期工作 在最后一行 源代码sampl
  • 如何调试 numpy 掩码

    这个问题与this one https stackoverflow com q 73672739 11004423 我有一个正在尝试矢量化的函数 这是原来的函数 def aspect good angle float planet1 goo
  • 将多索引转换为行式多维 NumPy 数组。

    假设我有一个类似于以下示例的 MultiIndex DataFrame多索引文档 http pandas pydata org pandas docs stable advanced html gt gt gt df 0 1 2 3 fir
  • 样本()和r样本()有什么区别?

    当我从 PyTorch 中的发行版中采样时 两者sample and rsample似乎给出了类似的结果 import torch seaborn as sns x torch distributions Normal torch tens
  • 从字典中绘制直方图

    我创建了一个dictionary计算 a 中出现的次数list每个键的内容 我现在想绘制其内容的直方图 这是我想要绘制的字典的内容 1 27 34 1 3 72 4 62 5 33 6 36 7 20 8 12 9 9 10 6 11 5
  • dask apply:AttributeError:“DataFrame”对象没有属性“name”

    我有一个参数数据框 并对每一行应用一个函数 该函数本质上是几个 sql queries 和对结果的简单计算 我正在尝试利用 Dask 的多处理 同时保持结构和界面 下面的例子有效并且确实有显着的提升 def get metrics row
  • 无法在我的程序中使用 matplotlib 函数

    我正在 Windows 10 中运行 Anaconda 安装 conda 版本 4 3 8 这是我尝试在 python 命令行中运行的代码 import matplotlib pyplot as plt x 1 2 3 4 y 5 6 7
  • Django Web 应用程序中的 SMTP 问题

    我被要求向使用 Django Python 框架实现的现有程序添加一个功能 此功能将允许用户单击一个按钮 该按钮将显示一个小对话框 表单以输入值 我确实编写了一些代码 显示电子邮件已发送的消息 但实际上 它没有发送 My code from
  • 将 Python Selenium 输出写入 Excel

    我编写了一个脚本来从在线网站上抓取产品信息 目标是将这些信息写入 Excel 文件 由于我的Python知识有限 我只知道如何在Powershell中使用Out file导出 但结果是每个产品的信息都打印在不同的行上 我希望每种产品都有一条
  • 旧版本的 spaCy 在尝试安装模型时抛出“KeyError: 'package'”错误

    我在 Ubuntu 14 04 4 LTS x64 上使用 spaCy 1 6 0 和 python3 5 为了安装 spaCy 的英文版本 我尝试运行 这给了我错误消息 ubun ner 3 NeuroNER master src pyt
  • 如何在supervisord中设置组?

    因此 我正在设置 Supervisord 并尝试控制多个进程 并且一切正常 现在我想设置一个组 以便我可以启动 停止不同的进程集 而不是全部或全无 这是我的配置文件的片段 group tapjoy programs tapjoy game1
  • 为什么我的 PyGame 应用程序根本不运行?

    我有一个简单的 Pygame 程序 usr bin env python import pygame from pygame locals import pygame init win pygame display set mode 400
  • 如何在 Qt 中以编程方式制作一条水平线

    我想弄清楚如何在 Qt 中制作一条水平线 这很容易在设计器中创建 但我想以编程方式创建一个 我已经做了一些谷歌搜索并查看了 ui 文件中的 xml 但无法弄清楚任何内容 ui 文件中的 xml 如下所示
  • PYTHON:从 txt 文件中删除 POS 标签

    我有以下 txt 文件 其中包含 POS 词性 http en wikipedia org wiki Part of speech tagging 每个单词的标签 不用 jj到 说 vb 我 ppss是 bedz愤怒 jj在 在 dt无与伦
  • 防止 Ada DLL 中的名称损坏

    有没有一种简单的方法可以防止在创建 Ada DLL 时 Ada 名称被破坏 这是我的 adb 代码 with Ada Text IO package body testDLL is procedure Print Call is begin

随机推荐