以下代码有什么问题吗?运行类似的代码我得到一个死锁,如果主线程试图获取锁定的锁,循环不会重新锁定它。
另外,由于我不能在没有"添加更多细节和#34;的情况下发布,在这种情况下会有什么好的细节?
import Tkinter
import threading
from time import sleep
from random import random
class Test(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.resizable(False, False)
self.grid()
self._button = Tkinter.Button(self, text='Click me', command=self._foo)
self._button.grid(column=0, row=0)
self._lock = threading.Lock()
def __enter__(self):
self._loopRunning = True
self._loopThread = threading.Thread(target=self._loop)
self._loopThread.start()
return self
def __exit__(self, exc_type, exc_val, traceback):
self._loopRunning = False
self._loopThread.join()
return False
def _loop(self):
while self._loopRunning:
print 'loop wants lock'
with self._lock:
print 'loop acquired lock'
self._button.configure()
sleep(random())
print 'loop should release lock'
print 'loop released lock'
sleep(1)
def _foo(self):
print 'foo wants lock'
with self._lock:
print 'foo acquired lock'
self._button.configure()
sleep(random())
print 'foo should release lock'
print 'foo released lock'
sleep(1)
if __name__ == '__main__':
with Test(None) as test:
test.mainloop()
答案 0 :(得分:3)
Tkinter不是线程安全的。使用队列进行Tkinter操作或使用线程安全版本mtTkinter(http://tkinter.unpythonic.net/wiki/mtTkinter)代替。 (我和mtTkinter一起去了。)
抱歉没有充分考虑以前提出的问题。之前已经解决了这个问题,例如于:
Threaded Tkinter script crashes when creating the second Toplevel widget
Possible locking issue in Tkinter application
Tkinter: How to use threads to preventing main event loop from "freezing"