de***********@gmail.com a écrit :
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
-------------------------------------------------------
"Would be" ?
I had to fix a couple problems to get your code running (namely,
importing threading and passing correct args to threading.Thread). Do
yourself a favour: next time, take time to post *working* code.
Anyway... Here's a (corrected) version with a couple prints here and
there. I think the output is clear enough:
import threading
import time
lookuptab = {'1.9.7.3':'Bangkok','1.9.60.3':'Sydney'}
results = dict((val, 0) for val in lookuptab.values())
def testt(loc):
global results
print "t-%s before: %s" % (loc,results)
results[loc] = 1
print "t-%s after: %s" % (loc,results)
def main():
for x in lookuptab.values():
thread = threading.Thread(target=testt,args=(x,))
thread.start()
print "main - no sleep: %s" % results
time.sleep(1)
print "main - 1s later : %s" % results
if __name__ == '__main__': main()
And the output is:
main - no sleep: {'Bangkok': 0, 'Sydney': 0}
t-Bangkok before: {'Bangkok': 0, 'Sydney': 0}
t-Bangkok after: {'Bangkok': 1, 'Sydney': 0}
t-Sydney before: {'Bangkok': 1, 'Sydney': 0}
t-Sydney after: {'Bangkok': 1, 'Sydney': 1}
main - 1s later : {'Bangkok': 1, 'Sydney': 1}
Now if I may give you an advice about threads and globals (or any other
kind of shared state): learn about semaphores. While this may not be an
issue in this snippet, race conditions is definitively something you
want to avoid whenever possible and cleanly handle else.
HTH