Python notes-simple thread pool multiprocessing. Pool

Source: Internet
Author: User

Multithreaded model design is a more complex logic, but python for multi-threaded processing has a variety of convenient class library, do not need too much tangled threading between the details of the operation. Like multiprocessing. Pool is one of them.

The official example is also very simple.

From multiprocessing import pooldef F (x):    return x*xif __name__ = = ' __main__ ':    pool = Pool (processes=4)              # STA RT 4 worker Processes    result = Pool.apply_async (f, [ten])    # evaluate "F" asynchronously    print Result.get ( timeout=1)           # prints "Unless" Your computer is *very* slow    print Pool.map (f, Range)          # prints "[0, 1, 4, ..., 81] "

Not a lot of detailed explanations. I have a piece of code on hand, I need to request hundreds of URLs, parse the HTML page to get some information, single-threaded for loop efficiency is very low, so see this module, want to use this to implement multithreaded analysis, the reference code is as follows:

From multiprocessing import pooldef analyse_url (URL):    #do something and this URL    return analysis_resultif __ name__ = = ' __main__ ':    pool = Pool (processes=10)    result = Pool.map (Analyse_url, Url_list)

Is indeed more than the previous single-threaded for loop url_list list, one request Analyse_url much faster, but the problem is that once the pool.map is not finished to ctrl-c interrupt the program, the program will be abnormal, can never quit, Refer to this post of StackOverflow and modify it to the following code:

#result = Pool.map (Analyse_url, url_list) result = Pool.map_async (Analyse_url, url_list). Get (120)

This solves the problem perfectly.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.