473,289 Members | 1,756 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 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 12745
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,...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.