python锁中的属性错误
我正在试验python锁并试图理解它们。我有以下三节课 LockMain.pypython锁中的属性错误,python,multithreading,Python,Multithreading,我正在试验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
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)
洛克2.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输入法1对象2输入法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__
有人能指出我做错了什么吗?试试,在你的初始化中:
self.lock=threading.lock()
你忘了实例化threading.lock
类
只需在LockMain中编写self.lock=threading.lock()
而不是self.lock=threading.lock