作者:woooooso_776 | 来源:互联网 | 2023-09-23 10:29
在单独的线程中调用相同函数的最佳方法是什么,并且每个实例都有一个单独的列表,其中包含返回值,而不重复函数?
例:
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
编辑:忘记提到我使用Python 2.7
解决方法:
使用ThreadPool
像这样的东西
from multiprocessing.pool import ThreadPool
pool = ThreadPool()
pool.map(function, list_containing_args)
P.S它的工作方式类似于多进程map.Each参数给出了一个新的线程.如果你有有限的资源或一个大的列表,你可以指定你想要产生的线程数
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