Python在单独的线程中调用相同函数的最佳方法是什么?

rbs*_*rbs 4 python python-multithreading python-2.7

在单独的线程中调用相同函数的最佳方法是什么,并且每个实例都有一个单独的列表,其中包含返回值,而不重复函数

例:

import threading


def function(a):

    returned_values = []

    ct = threading.currentThread() 
    while getattr(ct, "do_run", True):
        ret = do_something(a)
        returned_values.append(ret)


t1 = threading.Thread(target=function, args=("AAA",))
t2 = threading.Thread(target=function, args=("BBB",))
t3 = threading.Thread(target=function, args=("CCC",))

t1.start()
t2.start()
t3.start()

import time;time.sleep(10)
t1.do_run = t2.do_run = t3.do_run = False
Run Code Online (Sandbox Code Playgroud)

编辑:忘记提到我使用Python 2.7

vks*_*vks 7

使用ThreadPool

像这样的东西

from multiprocessing.pool import ThreadPool

pool = ThreadPool()
pool.map(function, list_containing_args)
Run Code Online (Sandbox Code Playgroud)

PS it works similar to multiprocess map.Each argument is given a new thread .You can specify the number of threads you want to spawn if you have limited resources or a big list

from multiprocessing.pool import ThreadPool
import subprocess
def func(ip):
    c=subprocess.Popen("ping -c 3 "+ip, shell=True, stdout=subprocess.PIPE)
    output, error= c.communicate()
    return output

pool = ThreadPool()
for i in  pool.map(func,["127.0.0.1", "www.google.com", "www.facebook.com"]):
    print i
Run Code Online (Sandbox Code Playgroud)