Til*_*ngh 5 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
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()
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
代码运行良好,直到两个线程分别尝试分别进入method1和method2时,我收到以下错误:
obj1输入法1 obj2输入法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__
Run Code Online (Sandbox Code Playgroud)
有人可以指出我在做什么错吗?
您忘了实例化threading.Lock该类。
只需写self.lock = threading.Lock()而不是self.lock = threading.Lock在您的LockMain.__init__()
| 归档时间: |
|
| 查看次数: |
1300 次 |
| 最近记录: |