Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)
I am trying to learn the threading topic in Python but not getting any idea what exactly is threading and why we use it? And also I want to know how are tasks being divided for multi-threading?

1 Answer

0 votes
by (108k points)

Kindly refer to the below code in which you just need to work with a few alternative URLs and then it will return the contents of the first one to respond.

import Queue

import threading

import urllib2

# Called by each thread

def get_url(q, url):

    q.put(urllib2.urlopen(url).read())

theurls = ["http://google.com", "http://yahoo.com"]

q = Queue.Queue()

for u in theurls:

    t = threading.Thread(target=get_url, args = (q,u))

    t.daemon = True

    t.start()

s = q.get()

print s

In the above case, the threading is practiced as a simple optimization in Python where each subthread will wait for a URL so that it can resolve and react, to put its contents on the queue; each thread won't hold the process up if the main thread gets terminates, and it will start all subthreads.

Related questions

0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Feb 10, 2021 in Python by ashely (50.2k points)

Browse Categories

...