Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6752435
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T13:02:39+00:00 2026-05-26T13:02:39+00:00

I have two questions about creating thread safe types in python, and one related

  • 0

I have two questions about creating thread safe types in python, and one related question about multiple inheritance.

1) Are there any problematic implications with using the following subclasses in my threaded application as a sort of “lazy” thread-safe type? I realize that whomever sets values which may be altered by other threads bears the responsibility to ensure those values are thread safe as well.

2) Another question I have is if there exists more prudent alternatives to these types within python in a typical installation.

Example:

from threading import Lock
from __future__ import with_statement

class safedict(dict):
    def __init__(self,*args,**kwargs):
        self.mylock=Lock(); 
        super(safedict, self).__init__(*args, **kwargs)
    def __setitem__(self,*args,**kwargs):
        with self.mylock:
            print " DEBUG: Overloaded __setitem__ has the lock now."
            super(safedict,self).__setitem__(*args,**kwargs)


class safeobject(object):
    mylock = Lock(); # a temporary useless lock, until we have a proper instance.
    def __init__(self,*args,**kwargs):
        self.mylock=Lock(); 
        super(safeobject, self).__init__(*args, **kwargs)
    def __setattr__(self,*args,**kwargs):
        with self.mylock:
            print " DEBUG: Overloaded __setattr__ has the lock now."
            super(safeobject,self).__setattr__(*args,**kwargs)

3) If both of the types defined above could be considered reasonably safe, what negative implications would be faced by using multiple inheritance to create a type that supported a mixture of both of these modifications, and does my example inherit those classes in the optimal order?

Example:

class safedict2(safeobject,dict):
    def __setitem__(self,*args,**kwargs):
        with self.mylock:
            print " DEBUG: Overloaded __setitem__ has the lock now."
            super(safedict2,self).__setitem__(*args,**kwargs)

Edit:
Just another example of another type inheriting both of the former types, and testing using ipython.

In [304]: class safedict3(safeobject,safedict):
   .....:         pass
   .....: 

In [305]: d3 = safedict3()
 DEBUG: Overloaded __setattr__ has the lock now.
 DEBUG: Overloaded __setattr__ has the lock now.

In [306]: d3.a=1
 DEBUG: Overloaded __setattr__ has the lock now.

In [307]: d3['b']=2
 DEBUG: Overloaded __setitem__ has the lock now.

In [308]: d3
Out[308]: {'b': 2}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T13:02:40+00:00Added an answer on May 26, 2026 at 1:02 pm

    As to your first and second questions, the dict, list, etc. types are already thread-safe. You do not have to add thread safety to them. However you may find this useful. It’s a decorator that basically implements the synchronized keyword from Java, using function scope to define a critical section. Using a similar approach it is possible to author a threading.Condition oriented decorator also.

    import threading
    
    def tryfinally(finallyf):
      u"returns a decorator that adds try/finally behavior with given no-argument call in the finally"
      def decorator(callable):
        def execute(*args, **kwargs):
          try: result = callable(*args, **kwargs)
          finally: finallyf()
          return result
        return execute
      return decorator
    
    def usinglock(lock):
      u"returns a decorator whose argument will acquire the given lock while executing"
      def decorator(function):
        body = tryfinally(lock.release)(function)
        def execute(*args, **kwargs):
          lock.acquire()
          return body(*args, **kwargs)
        return execute
      return decorator
    
    def synchronized(function):
      u"decorator; only one thread can enter the decorated function at a time; recursion is OK"
      return usinglock(threading.RLock())(function)
    

    Use it like this (and beware deadlocks if you overuse it):

    @synchronized
    def foo(*args):
      print 'Only one thread can enter this function at a time'
    

    On the third question, the Python tutorial states that the search order for inherited attributes is depth-first, left-first. So if you inherit (myclass, dict) then the __setitem__ method from myclass should be used. (In older versions of Python, this same section in the tutorial implied that this choice was arbitrary, but nowadays it appears to be quite deliberate.)

    I’m guessing from the Freudian slip of a semicolon in the posted source that you are new to Python but experienced in either Java or C#. If so you will need to keep in mind that attribute (method) resolution occurs at run time in Python, and that the classes as well as the instance are first-class objects that can be inspected/explored at run time.

    First the instance attribute dictionary is searched, then the class attributes, and then the parent class search algorithm starts. This is done with (conceptually) the equivalent of repeated hasattr(class_or_instance, attribute) calls.

    The below confirms that for “new-style” classes (classes that inherit from object, which in the 2.x language specification is optional), this resolution occurs each time the attribute is looked up. It is not done when the class (or subclass) is created, or when instances are created. (This was done in release 2.7.2.)

    >>> class Foo(object):
    ...   def baz(self):
    ...     print 'Original Foo.baz'
    ...
    >>> class Bar(Foo): pass
    ...
    >>> def newprint(self):
    ...   print 'New Foo.baz'
    ...
    >>> x = Foo()
    >>> y = Bar()
    >>> Foo.baz = newprint
    >>> a = Foo()
    >>> b = Bar()
    >>> map(lambda k: k.baz(), (x, y, a, b))
    New Foo.baz
    New Foo.baz
    New Foo.baz
    New Foo.baz
    [None, None, None, None]
    

    Replacing the method of class Foo changes the behavior of subclasses already defined and of instances already created.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two related questions about Web services: (1) I'm currently writing a set
I have two questions about java.awt.Shape . Suppose I have two Shape s, shape1
So I have two questions about HashMap s in Java: What is the correct
I have two noobish questions about Flash, Actionscript, Flex etc. 1) With these technologies
I have two examples I have a question about. Let me explain via some
I have a question about how to set up the relations between two models
I have a question about the singleton pattern. I saw two cases concerning the
Question I have two compilers on my hardware C++ and C89 I'm thinking about
I have a generic question about scope and encapsulation. Take two scenarios: Scenario 1:
I have an esoteric question involving Python metaclasses. I am creating a Python package

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.