[Tutor] knowing when a list is updated by a thread

Kent Johnson kent37 at tds.net
Wed Apr 23 14:07:47 CEST 2008


Vaibhav.bhawsar wrote:
> i have this code to print every new element in a list only when the list 
> length changes (while the list is updated by a thread running 
> elsewhere)...I was wondering if there is a pythonic way to do this? how 
> does one know when there is a new element in the list?
> 
> prevlength = 0
>     while geoCode.running:
>         places = geoCode.getResults() #returns a list with most up to 
> date elements..the list grows as the thread that updates it
>         if len(places) > prevlength:
>             print places[prevlength]
>             prevlength = len(places)

Ouch. This loop will chew up CPU time unless there is some kind of delay 
in getResults(). If the intent of the loop is to print every new value 
placed in the list, there is no guarantee that it will work.

If you are using the list to communicate results between two threads you 
should see if queue.Queue meets your needs. It is thread safe and has 
blocking access so you don't have to use a busy loop.

Otherwise you could use a threading.Condition to communicate between the 
threads.

Kent


More information about the Tutor mailing list