Need help in updating a global variable by a thread

Paul Hankin paul.hankin at gmail.com
Wed Oct 17 17:05:06 EDT 2007


On Oct 17, 7:48 pm, dedalusena... at gmail.com wrote:
> Hello Folks,
>
> My first posting here and I am a stuck in figuring out the exact way
> to update a global variable from within a function that doesnt return
> any value (because the function is a target of the thread and I dont
> know how exactly return would work in such a case). I am sure I am
> missing something very fundamental here. The essential pieces of my
> code that cause the problem would be something like this:
> ---------------------------------------------
> lookuptab = {'1.9.7.3':'Bangkok','1.9.60.3':'Sydney'}
>
> results = {}
>
> for val in lookuptab.values():
>     results[val]=0
>
> def testt(loc):
>        global results
>        results[loc] = 1
>        return results[loc]
>
> for x in lookuptab.values():
>       thread = threading.Thread(target=testt,args=(x))
>       thread.start()
> print results

When I try to run this I get a 6-arguments-instead-of-1 error because
you wrote args=(x) instead of args=(x,). I wonder why you don't see
this error?

Apart from that the code works, except you need to wait for the
threads to finish executing before you see the updated results. Have a
look at threading.join to see how you might do that.

--
Paul Hankin




More information about the Python-list mailing list