Phillip Martin Phillip Martin - 1 year ago 82
Python Question

value based thread lock

Forgive me if this has been asked before. I have looked around a lot, but I get the feeling that I don't have the proper vocabulary to find this by searching the web.

I have a multithreaded application in python. I want to be able to lock a certain block of code but only to other threads with a certain condition. Let me give an example: There are three threads,

. Each thread may run through the function
at any time. I don't want any two threads with
equal to each other to be able to access
Code block ALPHA
at the same time. However, I don't want to block threads whose
value is different. In this case, let's say
has a
bar == "cat"
and hits line
first. Before
hits line
, let's say
, with
bar == "cat"
hits line
. I would like for
to wait. But if
comes along, with
bar == "dog"
, I would like for it to be able to keep going.

(1) def foo(bar):
(3) lock(bar)
(4) # Code block ALPHA (two threads with equivalent bar should not be in here)
(5) unlock(bar)

As another note, the possible values for
are completely unpredictable but with a very high chance of collision.

Thank you for any help. The library I am looking at is the python threading library

Answer Source


Good news: I was able to reproduce the release_lock problem you encountered using my original answer via a somewhat crude testbed I cobbled together, and fix the issue using a counting mechanism (as you suggested) — at least a far as I can tell with my testing apparatus.

Now two separate shared dictionaries are used, one to keep track of the "names" or values associated with each lock as before, and another to keep track of how many threads are using each one at a given time.

As before, lock names must be hashable values so they can be used as keys in dictionaries.

import threading

namespace_lock = threading.Lock()
namespace = {}
counters = {}

def aquire_lock(value):
    with namespace_lock:
        if value in namespace:
            counters[value] += 1
            namespace[value] = threading.Lock()
            counters[value] = 1


def release_lock(value):
    with namespace_lock:
        if counters[value] == 1:
            del counters[value]
            lock = namespace.pop(value)
            counters[value] -= 1
            lock = namespace[value]


# sample usage    
def foo(bar):
    # Code block ALPHA (two threads with equivalent bar should not be in here)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download