【问题标题】:Python: What should I use multi-process or multi-thread in DB related tasks?Python:我应该在 DB 相关任务中使用多进程还是多线程?
【发布时间】:2018-02-03 08:58:26
【问题描述】:

这个thread解释了什么是CPU绑定、IO绑定问题。

鉴于Python 具有GIL 结构,有人推荐,

• Use threads for I/O bound problems
• Use processes, networking, or events (discussed in the next section) for CPU-bound problems

老实说,我无法完全直观地理解这些问题到底是什么。

这是我面临的情况:

crawl_item_list = [item1, item2, item3 ....]
for item in crawl_item_list:
    crawl_and_save_them_in_db(item)

def crawl_and_save_them_in_db(item):
    # Pseudo code    
    # crawled_items = crawl item from the web  // the number of crawled_items  is usually 200
    # while crawled_items:
    #    save them in PostgreSQL DB
    #    crawled_items = crawl item from the web    

这是我想通过并行进程或线程执行的任务。 (每个进程(或线程)都会有自己的crawl_and_save_them_in_db,并处理每个item)

在这种情况下,我应该在多进程(类似Pool)和多线程之间选择哪一个?

我认为由于这个任务的主要工作是storing the DB,这是一种IO绑定任务(希望是..),所以我必须使用多线程?我说的对吗?

需要你的建议。

【问题讨论】:

  • 只是抛出另一个流行语:如果您使用 python >= 3.4,您还可以查看 asnycio 包

标签: python multithreading multiprocessing python-multiprocessing


【解决方案1】:

这取决于将要存储的数据量。

如果它有数百万条记录,那么我强烈建议使用多处理方法。它可能是 python 的内置多处理或 3rd 方包。

如果数据更轻量级,则使用线程,甚至可以尝试 gevent。

在我的爬虫项目中,我首先从线程开始,然后转向 gevent,因为它更易于支持。在我的数据变成数百万条记录后,负责存储大量数据的部分移动到带有内部线程的单独的多处理模块中。支持和改进它有点不舒服,但现在工作几个小时的过程需要 5-10 分钟。

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2011-09-29
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2010-10-11
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多