@@ -0,0 +1,2605 @@
+from __future__ import unicode_literals, print_function, absolute_import, division%0A%0Afrom threading import Lock%0Atry:%0A    from queue import Queue%0Aexcept ImportError:%0A    from Queue import Queue%0A%0A%0Aclass ResourceLock(object):%0A    def __init__(self):%0A        self._resources = %7Bi: _ResourceLock() for i in range(0, 256)%7D%0A%0A    def lock(self, id):%0A        if not id:%0A            raise ValueError(%22The argument cannot be empty%22)%0A        self._resources%5Bord(id%5B-1%5D)%5D.lock(id)%0A%0A    def unlock(self, id):%0A        if not id:%0A            raise ValueError(%22The argument cannot be empty%22)%0A        self._resources%5Bord(id%5B-1%5D)%5D.unlock(id)%0A%0A%0Aclass _ResourceLock(object):%0A    def __init__(self):%0A        self._locker = Lock()%0A        self._waiters = %7B%7D%0A        self._resources = %7B%7D%0A%0A    def lock(self, id):%0A        while not self._lock(id):%0A            pass%0A%0A    def _lock(self, id):%0A        with self._locker:%0A            # Lock successfully.%0A            if id not in self._resources:%0A                self._resources%5Bid%5D = None%0A                return True%0A%0A            # Failed to lock, so wait that the other unlocks.%0A            if id not in self._waiters:%0A                self._waiters%5Bid%5D = waiter = Queue()%0A            else:%0A                waiter = self._waiters%5Bid%5D%0A%0A            _lock = Lock()%0A            _lock.acquire()%0A            waiter.put(_lock)%0A        _lock.acquire()%0A        _lock.release()%0A        return False%0A%0A    def unlock(self, id):%0A        with self._locker:%0A            if id not in self._resources:%0A                raise ValueError(%22The resource%5B%25s%5D is not locked%22)%0A%0A            self._resources.pop(id, None)%0A            waiter = self._waiters.get(id, None)%0A            if waiter is None:%0A                return%0A%0A            try:%0A                _lock = waiter.get_nowait()%0A                _lock.release()%0A            except Exception:%0A                pass%0A%0A            if waiter.empty():%0A                self._waiters.pop(id, None)%0A%0A%0Aif __name__ == %22__main__%22:%0A    from time import sleep%0A    from random import randint%0A    from threading import Thread%0A%0A    rl = ResourceLock()%0A    id = %220123456789%22%0A%0A    def test(flag):%0A        sleep(randint(0, 3))%0A        print(%22++++++%22, flag)%0A        rl.lock(id)%0A        print(flag, %22Lock%22)%0A        sleep(2)%0A        rl.unlock(id)%0A        print(flag, %22Unlock%22)%0A%0A    ts = %5B%5D%0A    ts.append(Thread(target=test, args=(%22111%22,)))%0A    ts.append(Thread(target=test, args=(%22222%22,)))%0A    ts.append(Thread(target=test, args=(%22333%22,)))%0A    ts.append(Thread(target=test, args=(%22444%22,)))%0A%0A    for t in ts:%0A        t.start()%0A    for t in ts:%0A        t.join()%0A    print(%22exit%22)%0A

Add the python example