如何与 ThreadPoolExecutor 并行运行代码?

我真的是线程的新手,这让我很困惑,我怎样才能并行运行这段代码?


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 title




page = 1


while True:


    with ThreadPoolExecutor() as executer:

        t = executer.submit(search_posts, page)


        title = t.result()


        print(title)


    if page == 20:

        break


    page += 1

另一个问题是我是否需要学习操作系统才能理解线程是如何工作的?


千万里不及你
浏览 138回答 1
1回答

PIPIONE

这里的问题是您正在ThreadPoolExecutor为每个页面创建一个新页面。要并行执行操作,只创建一个ThreadPoolExecutor并使用它的map方法:import concurrent.futures as cfimport requestsdef 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python