jmi*_*ite 7 python oop multithreading deadlock thread-safety
所以,我有一个多线程的python程序,目前正遭遇死锁.我打算通过子类化threading.Lock对象来记录锁获取:
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)
Run Code Online (Sandbox Code Playgroud)
当我尝试运行该程序时,我收到以下错误:
class DebugLock(threading.Lock):
TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是双重的:
是否可以将Lock对象子类化为我正在做的事情?
如果没有,在python中调试死锁的最佳方法是什么?
注意:我没有编写任何Python扩展.有一个类似的问题:如何使用python调试死锁? 但是,它涉及编译C++代码和使用GDB,因为我的代码是纯Python,所以我无法做到.
Rus*_*uss 15
你可以使用"有锁"而不是"锁定"的方法,如下所示:
import threading, traceback, sys
class DebugLock(object):
def __init__(self):
self._lock = threading.Lock()
def acquire(self):
print >>sys.stderr, "acquired", self
#traceback.print_tb
self._lock.acquire()
def release(self):
print >>sys.stderr, "released", self
#traceback.print_tb
self._lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, type, value, traceback):
self.release()
Run Code Online (Sandbox Code Playgroud)
因为你可能想要使用with你的锁语法(谁不会?),我已经在适当的上下文保护中抛出了.
用法如下:
>>> lock = DebugLock()
>>> with lock:
... print "I'm atomic!"
...
acquired <__main__.DebugLock object at 0x7f8590e50190>
I'm atomic!
released <__main__.DebugLock object at 0x7f8590e50190>
>>>
Russ 回答了重要问题(#2),我将回答问题#1。
看来不可能。threading.Lock() 是一个工厂函数(文档)。它调用 thread.allocate_lock() - 无法控制 Lock 对象的创建。您也无法对 thread.LockType 类定义(在 thread.pi 中公开的类骨架)进行猴子修补。
>>> thread.LockType.foo = "blah"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'thread.lock'
Run Code Online (Sandbox Code Playgroud)