Threading - Why Not Lock Objects Rather than lock the interpreter

Robert Brewer fumanchu at amor.org
Fri Dec 5 18:33:08 CET 2003


Fuzzyman wrote:
> Looking at threading code it seems that the Global Interpreter Lock is
> a bit of a 'brute force' way of preventing two threads attempting to
> access sensitive objects simultaneously....
> 
> Why not have a new type of object with a 'lock' facility... if an
> object is locked then any thread trying to access the object other
> than the one obtaining the lock is blocked until the lock is
> released..... rather than blocking *all* threads until one thread has
> finished with the object.....
> 
> It could be implemented as a new attribute of existing objects... or
> new types of objects.....

You mean like an RLock?

acquire( [blocking = 1]) 
    Acquire a lock, blocking or non-blocking.
    When invoked without arguments: if this thread already 
    owns the lock, increment the recursion level by one, 
    and return immediately. Otherwise, if another thread 
    owns the lock, block until the lock is unlocked. Once 
    the lock is unlocked (not owned by any thread), then 
    grab ownership, set the recursion level to one, and 
    return. If more than one thread is blocked waiting until 
    the lock is unlocked, only one at a time will be able 
    to grab ownership of the lock.


I use this for dictionaries, where I don't want it modified while
another thread is iterating over it:

import threading
class UnitCollection(dict):
    _mutex = None

    def __init__(self):
        self._mutex = threading.RLock()

    def acquire(self):
        self._mutex.acquire(True)
    
    def release(self):
        self._mutex.release()


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list