472,968 Members | 1,626 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,968 software developers and data experts.

Need help in updating a global variable by a thread

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
-------------------------------------------------------

results contain 0 instead of 1. Any help clearing my block is greatly
appreciated.

-Stephen

Oct 17 '07 #1
3 12718
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
Oct 17 '07 #2
On Oct 17, 7:48 pm, dedalusena...@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

Oct 17 '07 #3
First off, apologies for posting code that had issues. My bad and
promise next time to do due diligence.
>learn about semaphores.
Definitely will.
>While this may not be an issue in this snippet
Even when more than one user concurrently launches this python
program? Let me read up on this like you suggested and then get back.

Thanks for all your help,
-Stephen
On Oct 17, 4:57 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
dedalusena...@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- Hide quoted text -

- Show quoted text -

Oct 18 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: semi | last post by:
I am pretty new to using C++ and I can't figure this out. I have class PTM that starts a thread. There is an array of structure to be shared between PTM class and thread function. For some...
9
by: Tony Johansson | last post by:
Hello! I know it's bad design to use global variables. I just want to ask a question about them. Is global variables and global static variables the same. These are define outside any...
106
by: xtra | last post by:
Hi Folk I have about 1000 procedures in my project. Many, many of them are along the lines of function myfuntion () as boolean on error goto er '- Dim Dbs as dao.database Dim Rst as...
4
by: Marc Missire | last post by:
Hi, I have an issue below I'd love help with, involving a static variable, Application_Start, and a background thread. In global.asax.cs I have a static variable (outside any method) with a...
14
by: el_sid | last post by:
Our developers have experienced a problem with updating Web References in Visual Studio.NET 2003. Normally, when a web service class (.asmx) is created, updating the Web Reference will...
4
by: ddh | last post by:
Hi, I got a problem. I use a 'select' in a loop in the main thread, and when select return, a new thread will be created to handle the network event. And if the client send some special string,...
2
by: sorobor | last post by:
dear sir .. i am using cakephp freamwork ..By the way i m begener in php and javascript .. My probs r bellow I made a javascript calender ..there is a close button ..when i press close button...
8
by: yinglcs | last post by:
Hi, I read this article about global variable in c: http://www.phim.unibe.ch/comp_doc/c_manual/C/SYNTAX/glo_int_vars.html But I have a few questions 1. how can I declare the global variable...
0
by: Tim Rowe | last post by:
2008/9/24 <dudeja.rajat@gmail.com>: I'm surprised it runs at all -- as far as I can see "mod" in "mod.update(a)" and "print mod.a" is not defined. Did you mean "mod1"? If I change it to that,...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
3
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.