user9371654
user9371654

Reputation: 2398

How many threads are running in this python example?

I want to learn how to run a function in multithreading using python. In other words, I have a long list of arguments that I want to send to a function that might take time to finish. I want my program to loop over the arguments and call the functions on parallel (no need to wait until the function finishes fromt he forst argument).

I found this example code from here:

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

My question are:

1) I normally know that I have to specify a number of threads that I want my program to run in parallel. There is no specific number of threads in the code above.

2) The number of threads is something that varies from device to device (depends on the processor, memory, etc.). Since this code does not specify any number of threads, how the program knows the right number of threads to run concurrently?

Upvotes: 4

Views: 670

Answers (1)

Bayko
Bayko

Reputation: 1434

The threads are being created in the for loop. The for loop gets executed twice since there are two elements in theurls . This also answers your other two questions. Thus you end up with two threads in the program

plus main loop thread

Total 3

Upvotes: 1

Related Questions