|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +from threading import RLock |
| 4 | + |
| 5 | +_locks = {} |
| 6 | +def lock_for_object(obj, locks=_locks): |
| 7 | + return locks.setdefault(id(obj), RLock()) |
| 8 | + |
| 9 | +def synchronized(call): |
| 10 | + def inner(*args, **kwds): |
| 11 | + with lock_for_object(call): |
| 12 | + return call(*args, **kwds) |
| 13 | + return inner |
| 14 | + |
| 15 | +class Main(object): |
| 16 | + |
| 17 | + def __init__(self): |
| 18 | + self.attr = object() |
| 19 | + |
| 20 | + def b1(self): |
| 21 | + r = [] |
| 22 | + with lock_for_object(self.attr): |
| 23 | + r.append(0) |
| 24 | + return r |
| 25 | + |
| 26 | + def b2(self): |
| 27 | + r = [] |
| 28 | + with lock_for_object(self.attr): |
| 29 | + r.append(0) |
| 30 | + return r |
| 31 | + |
| 32 | + def m1(self): |
| 33 | + return id(lock_for_object(self)) |
| 34 | + |
| 35 | + def m2(self): |
| 36 | + return id(lock_for_object(self)) |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def c1(cls): |
| 40 | + return id(lock_for_object(cls)) |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def c2(cls): |
| 44 | + return id(lock_for_object(cls)) |
| 45 | + |
| 46 | + @synchronized |
| 47 | + def s1(self, *values, **kwargs): |
| 48 | + return [values, kwargs] |
| 49 | + |
| 50 | + @synchronized |
| 51 | + def s2(self, *values, **kwargs): |
| 52 | + return [values, kwargs] |
| 53 | + |
| 54 | + @classmethod |
| 55 | + @synchronized |
| 56 | + def cs1(cls, *values, **kwargs): |
| 57 | + return [cls, values, kwargs] |
| 58 | + |
| 59 | + @classmethod |
| 60 | + @synchronized |
| 61 | + def cs2(cls, *values, **kwargs): |
| 62 | + return [cls, values, kwargs] |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + x = Main() |
| 68 | + expected_count = 0 |
| 69 | + |
| 70 | + assert x.b1() == x.b2() |
| 71 | + expected_count += 1 # one for the attr, used twice |
| 72 | + |
| 73 | + assert x.c1() == x.c2() |
| 74 | + expected_count += 1 # one for the class, used twice |
| 75 | + |
| 76 | + assert x.m1() == x.m2() |
| 77 | + expected_count += 1 # one for the instance, used twice |
| 78 | + |
| 79 | + assert x.s1() == x.s2() |
| 80 | + expected_count += 2 # one for each instance method |
| 81 | + |
| 82 | + assert x.cs1() == x.cs2() |
| 83 | + expected_count += 2 # one for each class method |
| 84 | + |
| 85 | + assert expected_count == len(_locks) |
| 86 | + |
| 87 | + print '[PASS]' |
| 88 | + |
0 commit comments