Help us understand the problem. What is going on with this article?

Python - Simple multi-thread sample

More than 5 years have passed since last update.

Ref:
[1] - Stackoverflow - Multiple Threads in Python

This pattern is usually used in Http requesting. Since computing tasks might cause a lot of context switches, which might decrease the speed.

import threading

urlTaskList = [
# your tasks here
]

parallelism = 4

# here is the task you want to run
def subTask(urlList):
  import urllib2

  for url in urlList:
    data = urllib2.urlopen(url).read()

    # process the data here
    # ...


# this method is used to seperate task chunk
def splitChunk(tasks):
  """ Yield successive n-sized chunks from l.
  """
  for i in xrange(0, len(l), n):
    yield l[i:i+n]


threadList = list()
chunkList = list(splitChunk(urlTaskList))


for subChunk in chunkList:
  worker = threading.Thread(target=subTask, args=(subChunk))
  worker.start()
  threadList.append(worker)


# wait for every thread finish its work
for worker in threadList:
  worker.join()

The method splitChunk(taskList) above is from this post.

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away