multithreading - Reading the results from an infinite loop using threads in python -


i working python v.2.7 on windows 8.

my programme using threads. threads execute method named getdata() infinite time following:

  • makes current thread sleep time
  • calls comparevalues()
  • retrieve information comparevalues() , adds them list called mylist

the comparevalues() following:

  • generates random number
  • checks if less 5 or if greater or equal 5 , yields result along current thread's name

i save results of these threads list named mylist , print mylist.

problem: getdata() looping infinite time. how can access mylist retrieving results? approach in case. if remove while true: programm works fine.

code:

import time random import randrange import threading  mylist = [] def getdata(i):    while true:         print "sleep %d"%i         time.sleep(i)         data = comparevalues()         d in list(data):             mylist.append(d)  def comparevalues():         number = randrange(10)         name = threading.current_thread().name         if number >= 5:              yield "%s: greater or equal 5: %d  "%(name, number)         else:              yield "%s: less 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() t in threadlist:     t.join() print "the final list" print mylist 

thank time.

i see couple of inconsistencies may make code little bit more clear. instance:

  1. comparevalues() should return 'the result in string format......' , not yield. right? because function going evaluate 1 value @ time.
  2. getdata() should like:

    def getdata(i):     while true:         print "sleep %d"%i         time.sleep(i)         mylist.append(comparevalues()) 

exactly same reason said in previous point.

p.s.: don't know why code not formatting properly. sorry... :-(

i hope helps!


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -