Python 使用multiprocessing.dummy的并行请求
我尝试使用multiprocessing.dummy和report by progress运行并行get请求Python 使用multiprocessing.dummy的并行请求,python,python-3.x,parallel-processing,Python,Python 3.x,Parallel Processing,我尝试使用multiprocessing.dummy和report by progress运行并行get请求 from multiprocessing.dummy import Pool from functools import partial class Test(object): def __init__(self): self.count = 0 self.threads = 10 def callback(self, total, x):
from multiprocessing.dummy import Pool
from functools import partial
class Test(object):
def __init__(self):
self.count = 0
self.threads = 10
def callback(self, total, x):
self.count += 1
if self.count%100==0:
print("Working ({}/{}) cases processed.".format(self.count, total))
def do_async(self):
thread_pool = Pool(self.threads)#self.threads
input_list = link
callback = partial(self.callback, len(link))
tasks = [thread_pool.apply_async(get_data, (x,), callback=callback) for x in input_list]
return (task.get() for task in tasks)
start = time.time()
t = Test()
results = t.do_async()
end = time.time()`
由于称为全局解释器锁(GIL)的原因,操作的结果(与非并行请求相同)CPython本质上是单线程的。这意味着一次只能运行一个线程,即使有多个CPU核可用
multiprocessing.dummy
只是一个使用线程的包装器,所以这就是为什么您没有得到加速
要获得拥有多个CPU的好处,必须使用
多处理
本身。但是,基于发送和接收子进程的输入和输出数据的成本,存在间接费用。如果这样做的成本大于子进程完成的工作量,那么使用多处理
实际上会降低程序的速度。因此,在您的示例中,多处理
可能不会提高速度。这一点尤其正确,因为回调中的大部分工作都涉及打印到标准输出,池中的所有进程都必须同步到标准输出,以防止打印出垃圾。我在concurrent.futures中找到了解决方案:
import concurrent.futures as futures
import datetime
import sys
results=[]
print("start", datetime.datetime.now().isoformat())
start =time.time()
with futures.ThreadPoolExecutor(max_workers=100) as executor:
fs = [executor.submit(get_data, url) for url in link]
for i, f in enumerate(futures.as_completed(fs)):
results.append(f.result())
if i%100==0:
sys.stdout.write("line nr: {} / {} \r".format(i, len(link)))