【问题标题】:Python - Multiprocessing Pool Class: Can the Thread Function contain arguments?Python - 多处理池类:线程函数可以包含参数吗?
【发布时间】:2016-07-15 20:06:37
【问题描述】:

我想知道是否可以将参数传递到线程池功能中?

from multiprocessing.dummy import Pool as ThreadPool 

def mainFunc():
    myArray = ["A", "B", "C"]

    pool = ThreadPool(8) 
    pool.map(threadFunc, myArray)   # how is it possible to give >>threadFunc<< another argument >>text1<<
    pool.close()
    pool.join()

def threadFunc(text2):
    text1 = "Hello "                # this should be given as a argument  of the function
    print text1 + text2

mainFunc()

这是我想做的一个简单示例。如何将 text1 作为第二个参数提供给 threadFunc 函数?

已解决:

我用一个简单的全局可访问变量解决了这个问题......但这只是我现在遇到的问题的一个解决方案......改用multiprocessing.Process是一个更好的主意......

import sys
from multiprocessing.dummy import Pool as ThreadPool 

this = sys.modules[__name__] 

def mainFunc():
    myArray = ["A", "B", "C"]
    this.text1 = "Hello "

    pool = ThreadPool(8) 
    pool.map(threadFunc, myArray)   # how is it possible to give >>threadFunc<< another argument >>text1<<
    pool.close()
    pool.join()

def threadFunc(text2):
    print this.text1 + text2

mainFunc()

【问题讨论】:

    标签: python multithreading multiprocessing pool


    【解决方案1】:
    1. 官方 python 文档说

      map() 内置函数的并行等效项(尽管它仅支持一个可迭代参数)。它会一直阻塞,直到结果准备好。

      因此无法添加其他参数,但您始终可以将 text1 添加为 myArray 的最后一个元素,并在使用时将其弹出。

    2. 你也可以使用multiprocessing.Process而不是池。在这种情况下,您可以轻松添加另一个参数。

      def f(name):
          print 'hello', name
      
      if __name__ == '__main__':
          p = Process(target=f, args=('bob',))
          p.start()
          p.join()
      

    【讨论】:

    • 1.如果 text1 变量像“Hello”一样简单,这只是一个好主意.. 2. 将是解决这个问题的最佳主意 - 非常感谢 - D0N
    • 例如,@Don Python 可迭代列表可以包含不同的类型值。 text1可以是String,也可以是自定义的Class对象,当myArray的其他项是整数时可以是json:)
    【解决方案2】:

    您可以在元组或列表中传递任意数量的参数:

    from multiprocessing.dummy import Pool as ThreadPool 
    
    def mainFunc():
        myArray = ["A", "B", "C"]
        text1 = "Hello "
    
        pool = ThreadPool(8)
    
        # combine text1 with each element in myArray
        args_generator = ((text1, x) for x in myArray)
    
        pool.map(threadFunc, args_generator)
        pool.close()
        pool.join()
    
    def threadFunc(args):
        # unpack arguments
        text1, text2 = args
        print text1 + text2
    

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 2021-08-28
      • 1970-01-01
      • 2020-04-16
      • 2023-04-04
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      相关资源
      最近更新 更多