我写了一个使用线程锁的简单测试程序。这个程序的行为与预期不符,而Python解释器并没有报错。
test1.py:
from __future__ import with_statement
from threading import Thread, RLock
import time
import test2
lock = RLock()
class Test1(object):
def __init__(self):
print("Start Test1")
self.test2 = test2.Test2()
self.__Thread = Thread(target=self.myThread, name="thread")
self.__Thread.daemon = True
self.__Thread.start()
self.test1Method()
def test1Method(self):
print("start test1Method")
with lock:
print("entered test1Method")
time.sleep(5)
print("end test1Method")
def myThread(self):
self.test2.test2Method()
if __name__ == "__main__":
client = Test1()
raw_input()
test2.py:
from __future__ import with_statement
import time
import test1
lock = test1.lock
class Test2(object):
def __init__(self):
print("Start Test2")
def test2Method(self):
print("start test2Method")
with lock:
print("entered test2Method")
time.sleep(5)
print("end test2Method")
两个sleep同时执行了!这不是我使用锁时预期的结果。
当test2Method移动到test1.py中时,一切都正常。当我在test2.py中创建锁并在test1.py中导入它时,一切都正常。当我在一个单独的源文件中创建锁并同时在test1.py和test2.py中导入它时,一切都正常。
可能与循环导入有关。
但为什么Python没有对此进行抱怨呢?