Reputation: 5315
I am currently working with python v.2.7 on windows 8.
My programme is using threads. The threads execute a method named as getData()
for infinite time that does the following:
compareValues()
compareValues
() and adds them to a
list called myList
The compareValues()
does the following:
I save the results of these threads to a list named as myList
and then finally print this myList
.
Problem: As the getData()
is looping for infinite time. How can I access the myList
for retrieving the results? What would be a good approach in this case. If you remove the while True:
then the programm works fine.
Code:
import time
from random import randrange
import threading
myList = []
def getData(i):
while True:
print "Sleep for %d"%i
time.sleep(i)
data = compareValues()
for d in list(data):
myList.append(d)
def compareValues():
number = randrange(10)
name = threading.current_thread().name
if number >= 5:
yield "%s: Greater than or equal to 5: %d "%(name, number)
else:
yield "%s: Less than 5: %d "%(name, number)
threadList = []
wait = randrange(10)+1
t = threading.Thread(name = 'First-Thread', target = getData, args=(wait,))
threadList.append(t)
t.start()
wait = randrange(3)+1
t = threading.Thread(name = 'Second-Thread', target = getData, args=(wait,))
threadList.append(t)
t.start()
for t in threadList:
t.join()
print "The final list"
print myList
Thank you for your time.
Upvotes: 1
Views: 332
Reputation: 1087
I see a couple of inconsistencies that may help to make the code look a little bit more clear. For instance:
compareValues()
should return 'The result in string Format......' and not yield. Am I right? Because this function is going to evaluate only one value at a time.getData()
should look like:
def getData(i):
while True:
print "Sleep for %d"%i
time.sleep(i)
myList.append(compareValues())
Exactly for the same reason as I said in the previous point.
P.S.: I don't know why the code is not formatting properly. Sorry... :-(
I hope it helps!
Upvotes: 1