为了账号安全,请及时绑定邮箱和手机立即绑定

如何与 ThreadPoolExecutor 并行运行代码?

如何与 ThreadPoolExecutor 并行运行代码?

千万里不及你 2023-06-13 16:29:24
我真的是线程的新手,这让我很困惑,我怎样才能并行运行这段代码?def search_posts(page):    page_url = f'https://jsonplaceholder.typicode.com/posts/{page}'    req = requests.get(page_url)    res = req.json()        title = res['title']        return titlepage = 1while True:    with ThreadPoolExecutor() as executer:        t = executer.submit(search_posts, page)        title = t.result()        print(title)    if page == 20:        break    page += 1另一个问题是我是否需要学习操作系统才能理解线程是如何工作的?
查看完整描述

1 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

这里的问题是您正在ThreadPoolExecutor为每个页面创建一个新页面。要并行执行操作,只创建一个ThreadPoolExecutor并使用它的map方法:


import concurrent.futures as cf

import requests



def search_posts(page):

    page_url = f'https://jsonplaceholder.typicode.com/posts/{page}'

    res = requests.get(page_url).json()

    return res['title']



if __name__ == '__main__':

    with cf.ThreadPoolExecutor() as ex: 

        results = ex.map(search_posts, range(1, 21))

    for r in results:

        print(r)

请注意,使用if __name__ == '__main__'包装器是使您的代码更具可移植性的好习惯。


使用线程时要记住一件事;python.org如果您使用的是 CPython(最常见的Python 实现),线程实际上不会并行运行。


为了使内存管理不那么复杂,一次只能有一个线程在 CPython 中执行 Python 字节码。这是由 CPython 中的全局解释器锁(“GIL”)强制执行的。


好消息是,使用requests获取网页将花费大部分时间使用网络 I/O。通常,GIL 是在 I/O 期间释放的。


但是,如果您在辅助函数中进行计算(即执行 Python 字节码),则应改用 a ProcessPoolExecutor。


如果您使用 aProcessPoolExecutor并且在 ms-windows 上运行,则需要if __name__ == '__main__'使用包装器,因为在这种情况下Python 必须能够在没有副作用的情况下运行您的主程序。import


查看完整回答
反对 回复 2023-06-13
  • 1 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信