[Tutor] thread-safe singleton ?

Praveen Kumar pk1u@yahoo.com
Fri, 31 May 2002 15:35:25 -0700 (PDT)


Are either/both of the below singleton implementations
thread-safe ? I'm thinking not, b/c I think there are
cases where multiple threads can execute the statement
that sets the singleton instance, eg:


            Singleton.__instance = Singleton.__impl()

        Singleton.__single = self  

I'm new to python, so perhaps I'm missing something.
Thanks,

pk

-----

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558

class Singleton:
    """ A python singleton """

    class __impl:
        """ Implementation of the singleton interface
"""

        def spam(self):
            """ Test method, return singleton id """
            return id(self)

    # storage for the instance reference
    __instance = None

    def __init__(self):
        """ Create singleton instance """
        # Check whether we already have an instance
        if Singleton.__instance is None:
            # Create and remember instance
            Singleton.__instance = Singleton.__impl()

        # Store instance reference as the only member
in the handle
        self.__dict__['_Singleton__instance'] =
Singleton.__instance

    def __getattr__(self, attr):
        """ Delegate access to implementation """
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        """ Delegate access to implementation """
        return setattr(self.__instance, attr, value)


# Test it
s1 = Singleton()
print id(s1), s1.spam()

s2 = Singleton()
print id(s2), s2.spam()

# Sample output, the second (inner) id is constant:
# 8172684 8176268
# 8168588 8176268


-----------------------------

http://www.python.org/workshops/1997-10/proceedings/savikko.html

class Singleton:
    __single = None
    def __init__( self ):
        if Singleton.__single:
            raise Singleton.__single
        Singleton.__single = self  

def Handle( x = Singleton ):
    try:
        single = x()
    except Singleton, s:
        single = s
    return single    


__________________________________________________
Do You Yahoo!?
Yahoo! - Official partner of 2002 FIFA World Cup
http://fifaworldcup.yahoo.com