【问题标题】:Parallel processing / threading in PythonPython中的并行处理/线程
【发布时间】:2014-07-01 00:15:22
【问题描述】:

我希望在我的应用程序中使用多处理或线程来在后台执行一些耗时的操作。我看过很多例子,但我仍然无法实现我想要的。我正在尝试加载一堆图像,每个图像都需要几秒钟。我希望加载第一个图像,然后让其他图像在后台加载并存储在列表中(以供稍后使用),同时程序仍在执行其他操作(例如允许我的 GUI 上的控件仍然工作)。如果我有类似下面的示例,我该怎么做?我应该使用多处理还是线程?

class myClass():
    def __init__(self, arg1, arg2):
        #initializes some parameters

    def aFunction(self):
        #does some things
        #creates multiple processes or threads that each call interestingFunc
        #continues doing things

    def interestingFunc(self):
        #performs operations

m = myClass()

【问题讨论】:

    标签: python multithreading multiprocessing


    【解决方案1】:

    您可以使用任何一种方法。让您的ProcessThread 执行其工作,然后将结果放到Queue 上。然后,您的主线程/进程可以在闲暇时将结果从队列中取出并对其进行处理。这是一个多处理示例。

    from multiprocessing import Process, Queue
    
    def load_image(img_file, output_q):
        with open(img_file, 'rb') as f:
            img_data = f.read()
            # perform processing on img_data, then queue results
            output_q.put((img_file, img_data))
    
    result_q = Queue()
    images = ['/tmp/p1.png', '/tmp/p2.jpg', '/tmp/p3.gif', '/tmp/p4.jpg']
    
    for img in images:
        Process(target=load_image, args=(img, result_q)).start()
    
    for i in range(len(images)):
        img, data = result_q.get()
        # do something with the image data
        print "processing of image file %s complete" % img
    

    这假设处理顺序对您的应用程序并不重要,即来自每个文件的图像数据可能以任何特定顺序加载到队列中。

    【讨论】:

      【解决方案2】:

      这是并行执行多项操作的最简单方法,它将帮助您入门:

      来源

      import multiprocessing
      
      def calc(num):
          return num*2
      
      pool = multiprocessing.Pool(5)
      for output in pool.map(calc, [1,2,3]):
          print 'output:',output
      

      输出

      output: 2
      output: 4
      output: 6
      

      【讨论】:

        【解决方案3】:

        你可以试试这样的:

        from thread import start_new_thread
        
        pictureList = [ f for f in os.listdir(r"C:\your\picture\folder")]
        for pic in pictureList:
            start_new_thread(loadPicture,(pic,))
        
        def loadPicture(pic):
            pass # do some stuff with the pictures
        

        这是一个非常简单的方法,线程立即返回,也许您需要使用allocate_lock。如果您需要更多功能,可以考虑使用 threading 模块。小心将tuple 作为第二个参数传递给线程。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-10
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多