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:
- makes the current thread to sleep for some time
- calls the
compareValues() - retrieve the information from the
compareValues() and adds them to a list calledmyList
The compareValues() does the following:
- generates a random number
- checks if it is less than 5 or if it is greater than or equal to 5 and yields the result along with the current thread's name
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.
getData()method to loop infinitely?