473,513 Members | 2,469 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 12767
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
2935
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
2362
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
6345
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
6340
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
2913
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
1433
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
3137
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
3438
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
884
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,...
0
7259
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7158
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7098
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5683
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5085
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4745
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3232
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1592
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.