Skip to content

add threading.RWLock #53046

Closed as not planned
Closed as not planned

Description

@kristjanvalur
BPO 8800
Nosy @jcea, @pitrou, @kristjanvalur, @tiran, @njsmith, @asvetlov, @ofek, @elarivie
Files
  • rwlock.patch
  • Added-ShrdExclLock-to-threading-and-multiprocessing.patch
  • sharablelock.patch
  • Added-ShrdExclLock-to-threading-and-multiprocessing-2.patch
  • rwlock.patch
  • rwlock.patch
  • rwlock-sbt.patch
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = None
    created_at = <Date 2010-05-24.09:55:40.864>
    labels = ['type-feature', 'library']
    title = 'add threading.RWLock'
    updated_at = <Date 2020-01-15.09:20:07.038>
    user = 'https://github.com/kristjanvalur'

    bugs.python.org fields:

    activity = <Date 2020-01-15.09:20:07.038>
    actor = 'asvetlov'
    assignee = 'none'
    closed = False
    closed_date = None
    closer = None
    components = ['Library (Lib)']
    creation = <Date 2010-05-24.09:55:40.864>
    creator = 'kristjan.jonsson'
    dependencies = []
    files = ['17448', '27350', '27359', '27363', '27385', '27412', '27422']
    hgrepos = []
    issue_num = 8800
    keywords = ['patch', 'needs review']
    message_count = 63.0
    messages = ['106350', '106372', '106373', '106376', '106377', '106386', '168077', '168149', '171567', '171568', '171599', '171600', '171626', '171639', '171653', '171659', '171667', '171669', '171674', '171693', '171695', '171696', '171697', '171698', '171699', '171700', '171703', '171708', '171709', '171710', '171713', '171714', '171716', '171717', '171718', '171721', '171780', '171781', '171782', '171783', '171785', '171786', '171788', '171789', '171790', '171792', '171793', '171877', '171883', '171891', '171914', '171915', '171930', '171975', '171979', '172064', '172071', '172074', '274765', '274795', '287745', '360026', '360031']
    nosy_count = 15.0
    nosy_names = ['jcea', 'pitrou', 'kristjan.jonsson', 'christian.heimes', 'jyasskin', 'njs', 'asvetlov', 'neologix', 'vrutsky', 'sbt', 'mklauber', 'Sebastian.Noack', 'dan.oreilly', 'Ofekmeister', 'elarivie']
    pr_nums = []
    priority = 'normal'
    resolution = None
    stage = 'patch review'
    status = 'open'
    superseder = None
    type = 'enhancement'
    url = 'https://bugs.python.org/issue8800'
    versions = []

    Activity

    1. kristjanvalur commented on May 24, 2010

      kristjanvalurmannequin
      MannequinAuthor

      Provided is a patch, implementing a RWLock using a ConditionVariable and Lock.
      It has rdlock() and wrlock() methods, and an unlock() method, similar to the rwlock API in pthreads.
      It has context managers rdlocked() and wrlocked().
      In addition, it conforms to the RLock interface, with acquire() and release() being aliases to wrlock() and unlock() respectively and when used as a context manager, it gets a wrlock()
      There is no documentation yet, since this is just a proposal, but there are unit tests.

      See also bpo-8777 for another locking primitive, the Barrier.

    2. added
      stdlib
      type-feature
      on May 24, 2010
    3. jyasskin commented on May 24, 2010

      jyasskinmannequin
      Mannequin

      This patch doesn't apply cleanly against the py3k tree. Since Python 2.7 is in beta, and there's no 2.8, this can only go into python 3, so you should work against that tree.

      It's a bit annoying that the R in RWLock stands for a different word from in RLock. But I can't think of a better name.

      Hm, the test for RWLock should use a Barrier to check for multiple readers.

      I wonder if it makes sense to add a DeadlockError as a subclass of RuntimeError and throw that from trying to upgrade a read-lock to a write-lock.

      The docs should describe why upgrading a read-lock to a write-lock is banned, or else people will try to add the feature.

      test_wrrecursion should also check pure writer recursion. Oh, no, that's tested by RLockTests. Comment that please. The name of the test should probably mention write_then_read_recursion to distinguish it from write-then-write or read-then-write.

      test_readers_writers doesn't quite test enough. (Feel free to add another test rather than changing this one.) You want to test that readers can't starve writers. For example, say we have:
      lock = RWLock()
      done = False
      def r():
      with lock.rdlocked():
      if done:
      return
      _wait()
      def w():
      nonlocal done
      with lock.wrlocked():
      done = True
      readers = Bunch(r, 50)
      _wait()
      writers = Bunch(w, 1)
      readers.wait_for_finished()
      writers.wait_for_finished()

      In a naive implementation, there may never be a point where no reader has the lock held, and so the writer may never get in to tell them all to exit. I believe your implementation will already pass this test.

      spelling: mathced

      I'm not sure that "#threads will be few" is true for a read-lock, but I don't mind for the first implementation.

      Generally put a space after # when it introduces a comment, start comments with a capital letter, and end them with punctuation so we know you didn't stop typing early.

      In _rdlock could you flip the "not self.nw" condition? That way the else won't be a double-negative.

      Can self.rcond.wait() ever throw an exception? I suspect you should use try:finally: to guard the "self.nr -= 1"

      Why must the user hold a write lock to use Condition.wait? Semantically, a waiting on a read-lock would release the current thread's recursive read-locks, and all should be well.

      It looks like self.owning holds one copy of each thread's id for each re-entry by that thread. That wasn't obvious so deserves a comment.

      General API questions:

      1. Given that the other locking APIs use "acquire" and "release" instead of "lock" and "unlock", perhaps this class should use "rdacquire" and "wracquire"?
      2. I wonder if it helps actual code to be able to just call "unlock" instead of "rdunlock" and "wrunlock". Code releasing the lock should always know which kind of lock it holds.

      Otherwise, this looks basically correct. Thanks!

    4. pitrou commented on May 24, 2010

      @pitrou
      Member

      I'm not sure it's a good idea to have a default context manager, and default acquire/release methods. "In the face of ambiguity, refuse the temptation to guess".

      Is there any use in being able to use a RWLock inside a condition variable?

      Docstrings should be polished (e.g. typo "must be mathced with an release"). I think wrlocked() and rdlocked() deserve a docstring too.

      A style nit: generally, comments should be on their own line, before the code they comment. Also, there should be a space just after the "#" (see PEP-8 :-)).

    5. jyasskin commented on May 24, 2010

      jyasskinmannequin
      Mannequin

      In this case, "acquire" isn't ambiguous. All the other lock types actually acquire a write lock, so it makes sense to have the operation with the same name they use also acquire a write lock on this object.

      I realized that read/write locks are actually shared/exclusive locks, which might form the basis for a name that doesn't collide with RLock. Boost (http://www.boost.org/doc/libs/1_43_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex) uses shared_mutex for the concept, so SLock or SELock? There are some algorithms that write while the lock is acquired non-exclusive, so "shared" is actually a better name for the concept, even though posix and Java used read/write.

      The possibility of lock downgrading (turning an exclusive lock into a shared lock, without allowing any other exclusive acquisitions in the mean time) might inform your decision about how to name "unlock".

    6. pitrou commented on May 24, 2010

      @pitrou
      Member

      In this case, "acquire" isn't ambiguous. All the other lock types
      actually acquire a write lock, so it makes sense to have the operation
      with the same name they use also acquire a write lock on this object.

      Well, it looks like a strange kind of "consistency" to me, since other
      lock types are not dual. Both posix and Java APIs don't seem to imply
      that the write lock is the "default" lock in a RW lock. However, I'm not
      a synchronization specialist.

      I realized that read/write locks are actually shared/exclusive locks,
      which might form the basis for a name that doesn't collide with RLock.
      Boost
      (http://www.boost.org/doc/libs/1_43_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex) uses shared_mutex for the concept, so SLock or SELock?

      SELock looks ok, but I have to say that RWLock is more obvious (I don't
      need to do a search to guess that RW means "read/write").

    7. jyasskin commented on May 24, 2010

      jyasskinmannequin
      Mannequin

      You're definitely right that posix and java don't make these usable from the normal lock API. And I don't think it's essential that they be usable as RLocks, although it's nice for Conditions. I think what I'm actually saying is that, if you have an acquire() operation on RWLock, then it has to forward to the write lock. Forwarding to the read lock would have different semantics from RLock.acquire (2 threads could get in at once) and so would be incorrect.

      I agree that RWLock is more obvious. As long as the docs mention that it's equivalent to a shared/exclusive lock, I don't care that much about the name. Just throwing out ideas.

    8. kristjanvalur commented on Aug 13, 2012

      kristjanvalurmannequin
      MannequinAuthor

      I should add that on Windows, the new SRW that is part of Vista and Windows 7, uses locking, that is it favors neither readers or writers. It appears that nowadays the complex semantics of RWLocks have not really proven worthwile. See http://msdn.microsoft.com/en-us/magazine/cc163405.aspx

      Perhaps this proposed patch is overly complex.

    9. pitrou commented on Aug 13, 2012

      @pitrou
      Member

      Perhaps this proposed patch is overly complex.

      I don't know. Do you think relaxing the semantics would make the implementation significantly faster?
      (interesting link, btw)

    10. SebastianNoack commented on Sep 29, 2012

      SebastianNoackmannequin
      Mannequin

      I would love to see a reader/writer lock implementation shipped with Python's threading (and multiprocessing) module. But I have some issues with the patch:

      1. I would avoid the terms 'read' and 'write' as those terms are referring just to one of many use cases. A better and more generic name would be shared and exclusive lock.

      2. If we add a new synchronization primitive to the threading module we really should add it also to the multiprocessing module, for consistency and to keep switching between threading and multiprocessing as easy as it is right now.

      3. The methods rdlock() and wrlock() might even block if you call them with blocking=False. That's because of they acquire the internal lock in a blocking fashion before they would return False.

      4. As Antoine already pointed out, it is a bad idea to make acquiring the exclusive (write) lock, the default behavior. That clearly violates the Zen of Python, since explicit is better than implicit.

      5. The issue above only raises from the idea that the RWLock should provide the same API as the Lock and RLock primitives. So everywhere where a lock primitive is expected, you can pass either a Lock, RLock or RWLock. That is actually a good idea, but in that case you should explicitly specify, whether to pass the shared (read) or the exclusive (write) lock.

      Both issues 4. and 5. only raise from the idea that a shared/exclusive lock should be implemented as a single class. But having two different lock primitives, one for the shared lock and one for the exclusive lock and a function returning a pair of those, would be much more flexible, pythonic and compatible with existing lock primitives.

      def ShrdExclLock()
        class _ShrdLock(object):
          def acquire(self, blocking=True):
            ...
      
          def release(self, blocking=True):
            ...
      
          def __enter__(self):
            self.acquire()
            retrun self
      
          def __exit__(self, exc_value, exc_type, tb):
            self.release()
      
        class _ExclLock(object):
          def acquire(self, blocking=True):
            ...
      
          def release(self, blocking=True):
            ...
      
          def __enter__(self):
            self.acquire()
            retrun self
      
          def __exit__(self, exc_value, exc_type, tb):
            self.release()
      
        return _ShrdLock(), _ExclLock()

      # create a shared/exclusive lock
      shrd_lock, excl_lock = ShrdExclLock()

    11. kristjanvalur commented on Sep 29, 2012

      kristjanvalurmannequin
      MannequinAuthor

      Excellent points.
      For 3. however, I don't consider access to synchronized state to be "blocking". Blocking means to block while waiting for the lock. The internal lock is never held for any amount of time.
      Perhaps I'll cook up a new patch with these thoughts.

    12. SebastianNoack commented on Sep 29, 2012

      SebastianNoackmannequin
      Mannequin

      Using a lock as context manager is the same as calling lock.acquire(blocking=True) and it will in fact block while waiting for an other thread to release the lock. In your code, the internal lock is indeed just hold for a very short period of time while acquiring or releasing a shared or exclusive lock, but it might add up to a notable amount of time dependent on how much concurrent threads are using the same RWLock and how slow/busy your computer is.

      But what made me reconsider my point are following facts:

      1. For example, when you acquire a shared (read) lock in non-blocking mode and False is returned, you assume that an other thread is holding an exclusive (write) lock. But that isn't necessarily the case, if it also returns False, when the internal lock is acquired by an other thread for example in order to acquire or release another shared (read) lock.

      2. The internal lock must be acquired also in order to release a shared/exclusive lock. And the 'release' method (at least if implemented as for Lock and RLock) don't have a 'blocking' argument, anyway.

      For that reasons, I think it is ok to block while waiting for the internal lock, even if the shared/exclusive lock was acquired in non-blocking mode. At least it seems to lead to less unexpected side effects, than returning False in case the internal lock is acquired.

    13. SebastianNoack commented on Sep 30, 2012

      SebastianNoackmannequin
      Mannequin

      I've added a new patch, that implements a shared/exclusive lock as described in my comments above, for the threading and multiprocessing module.

    14. kristjanvalur commented on Sep 30, 2012

      kristjanvalurmannequin
      MannequinAuthor

      Yes, any "blocking" on the internal lock is not semantic blocking due to the use of the Shared lock itself, but merely a technical aspect, not semantically visible to the program. It is equivalent to the operating system pausing the thread, a techical detail opaque to the user program and somethign it cannot affect or influence.

      "Blocking" in the sense of the lock is due to the semantic use of the lock itself and the resources that it protects.

    15. 47 remaining items

    16. njsmith commented on Feb 14, 2017

      @njsmith
      Contributor

      Side note, in case anyone else finds themselves looking for the MSDN magazine article referenced above: it appears to be in the June 2007 issue, titled "CONCURRENCY: Synchronization Primitives New To Windows Vista".

      For the moment at least, this link seems to work: http://download.microsoft.com/download/3/A/7/3A7FA450-1F33-41F7-9E6D-3AA95B5A6AEA/MSDNMagazineJune2007en-us.chm

    17. elarivie commented on Jan 15, 2020

      elariviemannequin
      Mannequin

      Hi,

      Sorry to wake up a 10 years old discussion

      But I think that you might be interested in the following Python package that I created and maintain since few years now:

      https://pypi.org/project/readerwriterlock/
      

      1- It implements the three type of reader writer lock:

      • Read Priority
      • Write Priority
      • Fair Priority

      2- It matches the interface of python threading.Lock

      More specifically:
      def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
      def release(self) -> None:

      As you can see it supports the 'blocking' and the 'timeout' parameters) and it uses the same methods name

      3- It supports context manager (enter, __exit__)

      4- It is also possible (currently not well documented) to provide a lock factory when initializing a new reader writer lock to specify the internal lock mechanism to use (by default it uses threading.Lock).

          def __init__(self, lock_factory: Callable[[], Lockable] = lambda: threading.Lock()) -> None:

      This hidden feature allows to offer the possibility to implement your own lock mechanism (using port, file on disk, etc, ...) and the reader writer lock will internally use it (This open the door for multiprocessing locking)

    18. asvetlov commented on Jan 15, 2020

      @asvetlov
      Contributor

      Thanks for sharing, your project looks viable!

    19. transferred this issue fromon Apr 10, 2022
    20. zklaus commented on Jun 10, 2022

      @zklaus
      Contributor

      Is there still interest in having an RWLock in python itself? I personally think it would be an interesting and important addition.

      It seems this issue opens with a patch and quickly dives into implementation questions, but perhaps it would be good to have a general consensus on whether or not this should be added?

    21. pitrou commented on Jun 10, 2022

      @pitrou
      Member

      I do think a RWLock (or SELock, whetever the name :-)) would be useful.

      @gpshead What do you think?

    22. pitrou commented on Jun 10, 2022

      @pitrou
      Member

      That said, and for the record, I probably wouldn't review such a PR as I'm not active anymore.

    23. lrlunin commented on Aug 16, 2023

      @lrlunin

      What is an official status of this feature request? Would a sufficient solution/implementation added to cpython if there is any?

    24. pitrou commented on Aug 16, 2023

      @pitrou
      Member

      @lrlunin There is no "official" status :-)

      Would a sufficient solution/implementation added to cpython if there is any?

      Well, it will have to come with unit tests and proper documentation. It will also need to be reviewed and accepted by a motivated core developer.

      You may also start by asking on https://discuss.python.org/c/core-dev/23 to raise awareness and gather more opinions.

    25. gpshead commented on Aug 16, 2023

      @gpshead
      Member

      Given that https://pypi.org/project/readerwriterlock/ exists and there hasn't been a high demand for this, I suggest not adding it to the standard library. We provide the basics, things like that build upon them.

      I did skim over the rwlock-sbt.patch linked above (which appeared to be the most recent iteration of the 11y old proposals) and it isn't necessarily a bad thing, but a reader/writer shared/exclusive lock implementation is a complicated thing to maintain.

      If we were to add one... I think we should really not be reinventing the wheel ourselves, in pure Python. It'd be good to wrap the underlying platform's implementation such as pthread_rwlock on posix and presumably something equivalent available on Windows. Those will perform better.

      Similar to how we had a poorly performing pure python RLock implementation in the past until #47251 (bpo-3001) fixed it in ~3.2.

    26. rafalkrupinski commented on Jun 24, 2024

      @rafalkrupinski

      We provide the basics, things like that build upon them.

      How come toml is basics and RWLock is not?

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      stdlibtopic-multiprocessingtype-feature

      Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions