我正在尝试使用python锁并尝试理解它们。我有三个课程如下
LockMain.py
import time
from lock1 import *
from lock2 import *
import threading
class LockMain(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.lock = threading.Lock
self.obj1 = Lock1(self,"obj1")
self.obj2 = Lock2(self,"obj2")
threading.Thread(target=self.obj1.run).start()
threading.Thread(target=self.obj2.run).start()
def method1(self,str):
with self.lock:
print str+"Method1 entered"
time.sleep(5)
def method2(self,str):
with self.lock:
print str+"Method2 entered"
time.sleep(5)
if __name__ == "__main__":
obj = LockMain()
Lock1.py
import threading
import time
class Lock1(threading.Thread):
def __init__(self,obj,str):
threading.Thread.__init__(self)
self.obj = obj
self.str = str
def run(self):
count = 0
while True:
count += 1
print self.str+str(count)
time.sleep(1)
if count == 20:
print self.str+" entering method 1"
self.obj.method1(self.str)
Lock2.py
import threading
import time
class Lock2(threading.Thread):
def __init__(self,obj,str):
threading.Thread.__init__(self)
self.obj = obj
self.str = str
def run(self):
count = 0
while(True):
count += 1
print self.str+str(count)
time.sleep(1)
if count == 20:
print self.str+" entering method 2"
self.obj.method2(self.str)
代码运行正常,直到两个线程分别尝试进入method1和method2我收到以下错误: -
obj1进入方法1obj2进入方法2
Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Python27x64\lib\threading.py", line 530, in __bootstrap_inner
self.run()
File "C:\Python27x64\lib\threading.py", line 483, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\tsingh\Documents\lock1.py", line 18, in run
self.obj.method1(self.str)
File "C:/Users/tsingh/Documents/lockmain.py", line 17, in method1
with self.lock:
AttributeError: __exit__
Exception in thread Thread-5:
Traceback (most recent call last):
File "C:\Python27x64\lib\threading.py", line 530, in __bootstrap_inner
self.run()
File "C:\Python27x64\lib\threading.py", line 483, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\tsingh\Documents\lock2.py", line 18, in run
self.obj.method2(self.str)
File "C:/Users/tsingh/Documents/lockmain.py", line 23, in method2
with self.lock:
AttributeError: __exit__
有人可以指出我在这里做错了什么吗?
答案 0 :(得分:5)
您忘记实例化threading.Lock
类。
只需在self.lock = threading.Lock()
self.lock = threading.Lock
而不是LockMain.__init__()
答案 1 :(得分:2)
在您的初始化中尝试:self.lock = threading.Lock()