Creating objects in thread created with subclass

Jeff Shannon jeff at ccvcorp.com
Tue Apr 9 20:01:44 EDT 2002


In article <mailman.1018365202.7991.python-list at python.org>, 
narnett at mccmedia.com says...

> [...] Here's my question -- in the "run" method of
> Aahz's example, if I create my retriever object in an ordinary way, then all
> of the threads will be sharing the same object, right?  And that most
> definitely will not work.  

No, that's not correct.  If you create an object in the Run 
method of your threading.Thread subclass, then you will create a 
new instance of that object for *each* instance of your subclass, 
so each thread will have a unique object created for it.  Since 
you're using a thread pool, then you'll be re-using that object 
each time that you re-use that thread, but ThreadA will have a 
different instance of it than ThreadB.

> So, I could create objects with 'eval' or 'exec'
> to generate unique names for each thread -- but is that the right way to do
> it?  

No, that is definitely *not* the right way to do it -- as I keep 
saying, exec/eval() are very rarely the right way to do it, 
whatever "it" may be.  ;)

> Or should I stop using objects there and directly use the functions
> from my classes.  I haven't looked at a whole lot of examples, but so far,
> the latter seems to be the way people do it.

You should be fine using your objects.  Just remember that, 
unless you explicitly create a new object when the thread is 
pulled from the thread pool, you'll have a one-to-one 
correspondence between your threads and your object.  (Presuming 
that you're creating only one such object in the Run() method...)

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list