473,399 Members | 2,858 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,399 software developers and data experts.

Are arguments to python __init__ method passed as pointers? In a threading.Thread?

Hi,

I'm new to python, and having problems instantiating classes. My main method has a couple of lines like this:
Expand|Select|Wrap|Line Numbers
  1.     debug = False
  2.     stats_d = {"cpu":[],"foo":[],"bar":[],"baz":[]}
  3.     cpu.CpuMonitor(debug,stats_d["cpu"]).start()
  4.     db.UpdateDatabase(debug,stats_d).start()
  5.  
And CpuMonitor looks like this:
Expand|Select|Wrap|Line Numbers
  1. class CpuMonitor (threading.Thread):
  2.  
  3.     def __init__ (self, debug, resultslist):
  4.  
  5.         threading.Thread.__init__(self)        
  6.  
  7.         self.debug = debug
  8.         self.resultslist = resultslist
  9.  
  10.     def run ( self ) :
  11.          # some stuff
  12.          items = ('stuff','morestuff','otherstuff')
  13.          self.resultslist.append(items)
  14.  
I was expecting to be able to populate my dictionary lists within CpuMonitor and then use them within the UpdateDatabase thread. However, while the local copy of CpuMonitor does create entries in it's resultslist variable, neither the main method or the UpdateDatabase thread see anything other than an empty list for each dictionary entry.

The same problem occurs with the debug variable. Setting debug to true within the CpuMonitor thread turns on debug for CpuMonitor, but not the rest of the program.

This leads me to believe that the way I've built the __init__ method is creating copies of the variables rather than pointers to the originals. Is that the case? If so, how to I achieve what I'm trying to do (preferrably without using global variables)?

Many thanks,
Matt.
Apr 30 '07 #1
2 1894
bvdet
2,851 Expert Mod 2GB
Hi,

I'm new to python, and having problems instantiating classes. My main method has a couple of lines like this:

debug = False
stats_d = {"cpu":[],"foo":[],"bar":[],"baz":[]}
cpu.CpuMonitor(debug,stats_d["cpu"]).start()
db.UpdateDatabase(debug,stats_d).start()

And CpuMonitor looks like this:

class CpuMonitor (threading.Thread):

def __init__ (self, debug, resultslist):

threading.Thread.__init__(self)

self.debug = debug
self.resultslist = resultslist

def run ( self ) :
# some stuff
items = ('stuff','morestuff','otherstuff')
self.resultslist.append(items)

I was expecting to be able to populate my dictionary lists within CpuMonitor and then use them within the UpdateDatabase thread. However, while the local copy of CpuMonitor does create entries in it's resultslist variable, neither the main method or the UpdateDatabase thread see anything other than an empty list for each dictionary entry.

The same problem occurs with the debug variable. Setting debug to true within the CpuMonitor thread turns on debug for CpuMonitor, but not the rest of the program.

This leads me to believe that the way I've built the __init__ method is creating copies of the variables rather than pointers to the originals. Is that the case? If so, how to I achieve what I'm trying to do (preferrably without using global variables)?

Many thanks,
Matt.
It seems to me you should instantiate your CpuMonitor class before calling a Thread object method. Test:
Expand|Select|Wrap|Line Numbers
  1. import threading
  2.  
  3. class CpuMonitor (threading.Thread):
  4.  
  5.     def __init__ (self, debug, resultslist):
  6.  
  7.         threading.Thread.__init__(self)        
  8.  
  9.         self.debug = debug
  10.         self.resultslist = resultslist
  11.  
  12.     def run (self):
  13.          # some stuff
  14.          items = ('stuff','morestuff','otherstuff')
  15.          self.resultslist.append(items)
  16.  
  17. debug = False
  18. stats_d = {"cpu":[],"foo":[],"bar":[],"baz":[]}
  19. t = CpuMonitor(debug,stats_d["cpu"])
  20. t.start()
  21. #UpdateDatabase(debug,stats_d).start()
  22. for key in t.__dict__:
  23.     print '%s = %s' % (key, t.__dict__[key])
  24.  
  25. '''
  26. >>> _Thread__block = <Condition(<thread.lock object at 0x0094E380>, 0)>
  27. _Thread__name = Thread-5
  28. _Thread__daemonic = False
  29. debug = False
  30. _Thread__started = True
  31. _Thread__stderr = <pywin.framework.interact.DockedInteractiveView instance at 0x00D76300>
  32. _Thread__target = None
  33. resultslist = [('stuff', 'morestuff', 'otherstuff')]
  34. _Thread__kwargs = {}
  35. _Verbose__verbose = False
  36. _Thread__args = ()
  37. _Thread__stopped = True
  38. _Thread__initialized = True
  39. >>> t.resultslist
  40. [('stuff', 'morestuff', 'otherstuff')]
  41. >>> stats_d
  42. {'baz': [], 'foo': [], 'bar': [], 'cpu': [('stuff', 'morestuff', 'otherstuff')]}
  43. >>>
  44. '''
Your global dictionary 'stats_d' is updated. Is this what you expected?
When posting code, please use code tags (see reply guidelines).
Apr 30 '07 #2
bartonc
6,596 Expert 4TB
Hi,

I'm new to python, and having problems instantiating classes. My main method has a couple of lines like this:
Expand|Select|Wrap|Line Numbers
  1.     debug = False
  2.     stats_d = {"cpu":[],"foo":[],"bar":[],"baz":[]}
  3.     cpu.CpuMonitor(debug,stats_d["cpu"]).start()
  4.     db.UpdateDatabase(debug,stats_d).start()
  5.  
And CpuMonitor looks like this:
Expand|Select|Wrap|Line Numbers
  1. class CpuMonitor (threading.Thread):
  2.  
  3.     def __init__ (self, debug, resultslist):
  4.  
  5.         threading.Thread.__init__(self)        
  6.  
  7.         self.debug = debug
  8.         self.resultslist = resultslist
  9.  
  10.     def run ( self ) :
  11.          # some stuff
  12.          items = ('stuff','morestuff','otherstuff')
  13.          self.resultslist.append(items)
  14.  
I was expecting to be able to populate my dictionary lists within CpuMonitor and then use them within the UpdateDatabase thread. However, while the local copy of CpuMonitor does create entries in it's resultslist variable, neither the main method or the UpdateDatabase thread see anything other than an empty list for each dictionary entry.

The same problem occurs with the debug variable. Setting debug to true within the CpuMonitor thread turns on debug for CpuMonitor, but not the rest of the program.

This leads me to believe that the way I've built the __init__ method is creating copies of the variables rather than pointers to the originals. Is that the case? If so, how to I achieve what I'm trying to do (preferrably without using global variables)?

Many thanks,
Matt.
The ONLY thread-safe way to pass data between threads is to use a queue.Queue.
Create the Queue in the main thread and pass it to you backgroud task.
In the background task use myQueue (made up name for the instance of Queue) .put(data).
In the main thread, use theQueue.get().

I'd post some actual code, but I'm currently without a machine that has both internet and python.

Hope that helps,
Barton
Apr 30 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

19
by: Jane Austine | last post by:
As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException....
2
by: Neil Hodgson | last post by:
I am seeing some problems with threads on Red Hat Linux 9.0. With no LD_ASSUME_KERNEL environment variable set, a large proportion, possibly 20%, of threads do not run. They are created OK and...
3
by: Daniel Schüle | last post by:
Hello Ng, I was playing around with pymedia module and I succeeded when I used complementation instead of inheritance .. but then I was forced to wrap simple methods of sound.Output like...
10
by: Andrew Bullock | last post by:
Hi, code: myClass x = new myClass(); x.dosomethingwith(x,y); How do i make dosomethingwith(x,y) run on a separate thread, and then inform the main thread when it has finished?
9
by: zxo102 | last post by:
Hi everyone, I am using a python socket server to collect data from a socket client and then control a image location ( wxpython) with the data, i.e. moving the image around in the wxpython frame....
5
by: momobear | last post by:
I feel really puzzled about fellowing code, please help me finger out what problem here. import threading class workingthread(threading.Thread): def __init__(self): self.quitEvent =...
4
by: Steven D'Aprano | last post by:
When you call a new-style class, the __new__ method is called with the user-supplied arguments, followed by the __init__ method with the same arguments. I would like to modify the arguments...
1
by: tsic | last post by:
Bonjour, je suis bloqué ilya preque 2 semaines dans le code suivant. je veut que le client et le serveur envoyent leurs message d'une maniere comme msn. je crois qu'ilya quelque chose à ajouter dans...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.