[Tutor] threading.currentThread() always same across request ?

Arun Kumar PG arunkumarpg at gmail.com
Sun Apr 15 07:06:54 CEST 2007


Thx guys.

now quick question on the usage of thread local storage.

In my case I have the below object model:

class Base(object):'
  def __init__(self):
    self.__service = None
  def _GetService():
    if not hasattr(threading.currentThread(), 'service'):
      threading.currentThread().service = Service()
      self.__service =  threading.currentThread().service

    return self.__service

class Child1(Base):'
  def DoSomething():
    service = self._GetService()
    # use service

class Child2(Base):'
  def DoSomething():
    service = self._GetService()
    # use service

The above Child classes are used by a controller:

class Controller(object):
  def process(self):
    c1 = Child1()
    c1.DoSomething()
    ....
    ...
    c2 = Child2()
    c2.DoSomething()

Using the above technique the "service" is instantiated only one time i.e.
as soon as I create the first instance of the Child class abd associated
with the current thread for future instantiation of any Child class.

Now in this scenario how can I use thread local ? Where do I keep the thread
local object as in my case I am instantiating the Child classes ? Using
currentThread() always gives me the same thread instance for a given request
and I can bypass instantiating the Service class by simply returning the
"service" attribute already attached to the current thread.

Any suggestion appreciated!

- A






On 4/15/07, Kent Johnson <kent37 at tds.net> wrote:
>
> Andreas Kostyrka wrote:
> > * Kent Johnson <kent37 at tds.net> [070414 19:53]:
> >> That's a good point. Does anyone know when to prefer threading.local()
> >> vs thread attributes?
> > It's design question, I guess:
> >
> > *) if you have thread subclasses, then use thread attributes.
> > *) if you have standard threads, then use thread.local().
> >
> > The idea is, that it's "rude" to stick attributes on an object that is
> > not owned by you.
> >
> > Rationale:
> > *) Somebody might decide to make threading.Thread be a new style
> > object with __slots__ => your code breaks.
> >
> > I know, it's unprobably, but if you derive a subclass, you can be at
> > least sure that the object will have a __dict__ ;)
>
> If you use threading.local() you can be sure the names you use don't
> conflict with any attributes of the thread.
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070415/9dc697bb/attachment-0001.html 


More information about the Tutor mailing list