Writing a thread-safe class



Hello

I would like to write a class with methods that can be accessed by many threads at the same time.

For this I have a lock attribute in my class obtained with threading.Lock(), in the constructor, and every method begins by acquiring the lock and ends by releasing it

My problem is that the lock is still an attribute of the class, and the very expression self.lock in the statement self.lock.acquire() is performed before locking, thus not being thread-safe.

If I am correct self is a dictionary of object attributes, and if another thread has the lock and creates a new attribute, or deletes one, in the same time with my lookup for self.lock, than the lookup is compromised.

How do people create thread-safe classes in python ?

Thank you,
Timothy Madden
.



Relevant Pages

  • Re: Making CLOS thread-safe, how difficult?
    ... quite clearly NOT thread-safe. ... I saw that SBCL wraps a good number of CLOS ... I would hate to have to grab a lock to ...
    (comp.lang.lisp)
  • Re: Making CLOS thread-safe, how difficult?
    ... I saw that SBCL wraps a good number of CLOS ... I would hate to have to grab a lock to ... Stuff like this argues for a sort of immutable structure system, something that allows each thread to use a consistent set of bindings until its stack frame returns past some boundary. ... Don't know if it was truly thread-safe, ...
    (comp.lang.lisp)
  • Re: multi threading in C#
    ... the queue itself does. ... Let's assume the Queue class is defined as not thread-safe. ... But then, if the class is defined as not thread-safe, why would it be doing any locking itself? ... Interestingly at least part of the issue comes about because of the use of the Monitor class, which apparently has knowledge of the compiler keyword "lock". ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: multi threading in C#
    ... the queue itself does. ... Let's assume the Queue class is defined as not thread-safe. ... It may be doing locking in a different way, ... It may have some internal data structure that it needs a lock ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: FYI: merging TCP, UDP, netisr locking changes
    ... This has implied non-trivial changes to our inpcb locking model, netisr code, etc. Detailed information will appear in commit messages as I go; some elements, such a programming of card filters based on setting TCP socket options, are very much a work in progress. ... After a series of smaller commits, I've just merged some initial decomposition of the pcbinfo lock into an additional pcbhash lock, which changes lock ordering and lookup with respect to inpcbs significantly ... all connections (including, awkwardly, certain UDP multicast receive ...
    (freebsd-current)