可以在Python中对Lock()对象进行子类化吗?如果没有,还有其他调试死锁的方法吗?
所以,我有一个多线程python程序,它目前正遭受死锁。我打算通过子类化线程来记录锁获取。锁对象:可以在Python中对Lock()对象进行子类化吗?如果没有,还有其他调试死锁的方法吗?,python,multithreading,oop,thread-safety,deadlock,Python,Multithreading,Oop,Thread Safety,Deadlock,所以,我有一个多线程python程序,它目前正遭受死锁。我打算通过子类化线程来记录锁获取。锁对象: import traceback class DebugLock(threading.Lock): def acquire(self): print >>sys.stderr, "acquired", self #traceback.print_tb threading.Lock.acquire(self) def r
import traceback
class DebugLock(threading.Lock):
def acquire(self):
print >>sys.stderr, "acquired", self
#traceback.print_tb
threading.Lock.acquire(self)
def release(self):
print >>sys.stderr, "released", self
#traceback.print_tb
threading.Lock.release(self)
当我尝试运行该程序时,出现以下错误:
class DebugLock(threading.Lock):
TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
因此,我的问题有两个:
import threading, traceback, sys
class DebugLock(object):
def __init__(self):
self._lock = threading.Lock()
def acquire(self):
print("acquired", self)
#traceback.print_tb
self._lock.acquire()
def release(self):
print("released", self)
#traceback.print_tb
self._lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, type, value, traceback):
self.release()
我在这里加入了适当的上下文保护,因为您可能希望在锁中使用with
语法(谁不会呢?)
用法如下:
>>> lock = DebugLock()
>>> with lock:
... print("I'm atomic!")
...
acquired <__main__.DebugLock object at 0x7f8590e50190>
I'm atomic!
released <__main__.DebugLock object at 0x7f8590e50190>
>>>
>>>lock=DebugLock()
>>>带锁:
... 打印(“我是原子的!”)
...
获得
我是原子弹!
释放
>>>
罗斯回答了重要的问题(#2),我将回答问题#1 似乎不可能。threading.Lock()是一个工厂函数()。它调用thread.allocate_lock()-无法控制锁对象的创建。您也不能monkeypatch thread.LockType类定义(thread.pi中公开的类骨架)
>thread.LockType.foo=“blah”
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无法设置内置/扩展类型“thread.lock”的属性
如果您希望执行类似于继承的操作而不出现此错误,我建议您尝试
import traceback
from threading import Lock
class DebugLock():
def __init__(self,lock = None):
self.lock = lock or Lock()
# normally done with __dict__
for command in dir(self.lock):
self.__dict__[command] = getattr(self.lock,command)
我使用self.\uuu dict.\uuu.update(lock.\uu dict.\uuu)的常规方法似乎不起作用。我用锁定代码测试了这个
X = DebugLock()
y = X.lock
Y = DebugLock(y)
X.acquire()
Y.acquire()
X.release()
Y.release()
这是挂起的,所以我认为它起作用了。谢谢,尽管如此!
X = DebugLock()
y = X.lock
Y = DebugLock(y)
X.acquire()
Y.acquire()
X.release()
Y.release()