sherin
sherin

Reputation: 355

Python Thread issues with passing thread object inside for loop

Why is this code not giving all the list variables from the "servers" list? I think it was supposed to print all those hosts instead of it only printing the last variable in the list.

#!/usr/bin/python
import time
import threading
from threading import Thread
import os,sys
class InitThread(Thread):
    def  __init__(self,threadID, host):
        self.host = host
        self.threadID = threadID
        super(InitThread, self).__init__()

    def run(self):
        print host




servers=[ 'yahoo.com','google.com','10.0.0.10','10.0.0.0.11','10.0.0.12']

jobs = []
threadID = 1
for host in servers:
    t=InitThread(threadID,host)
    jobs.append(t)
    threadID += 1
for t in jobs:
    t.start()
    t.join()    

After executing the above script I will get the output as follows,

# python foo.py 
10.0.0.12
10.0.0.12
10.0.0.12
10.0.0.12
10.0.0.12

Upvotes: 0

Views: 48

Answers (1)

merlin2011
merlin2011

Reputation: 75629

You are printing a class variable host in your run method, rather than the instance variable host. Since that variable is shared among all instances of InitThread and the last assignment made it the last element of the list, you will always get the last element of the list printed.

You can fix it by prepending self.

#!/usr/bin/python
import time
import threading
from threading import Thread
import os,sys
class InitThread(Thread):
    def  __init__(self,threadID, host):
        super(InitThread, self).__init__()
        self.host = host
        self.threadID = threadID

    def run(self):
        print self.host

Upvotes: 2

Related Questions