Implementation instance of the python thread pool

Source: Internet
Author: User
This article mainly introduces the implementation method of the python thread pool. the code is simple and practical for your reference:

The code is as follows:

#-*-Coding: UTF-8 -*-
Import Queue
Import threading
Import urllib
Import urllib2
Import OS

Def down (url, n ):
Print 'item' + str (n) + 'start'
Filename = urllib2.unquote (url). decode ('utf8'). split ('/') [-1]
Urllib. urlretrieve (url, filename)
Print 'item' + str (n) + 'finish'

Def worker ():
While True:
I = q. get ()
Url = I [0]
N = I [1]
Down (url, n)
Q. task_done ()

If _ name __= = "_ main __":

Num_worker_threads = 100

F=open('url.txt ')
L = f. readlines ()
Q = Queue. Queue ()
For I in range (num_worker_threads ):
T = threading. Thread (target = worker)
T. daemon = True
T. start ()

For I in range (0, len (l )):
Q. put (l [I], I ))

Q. join ()

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: 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.