下面这段python的多线程代码为什么运行不起来,说是函数没有加锁的属性
importadihe,string,socket,time,os,sys,threadingnum=0classThread():lock=threading.Lock...
import adihe,string,socket,time,os,sys,threading
num=0
class Thread():
lock=threading.Lock()
def lock(self):
self.lock.acquire()
def unlock(self):
self.lock.release()
def p2(a):
global num
thread.lock()
num+=1
print(a+num)
time.sleep(3)
thread.unlock()
def p1(a):
for i in range(3):
info='this %s thread'%(i)
p2(info)
def main():
for i in range(3):
p1(i)
if __name__ == '__main__':
thread=Thread()
main() 展开
num=0
class Thread():
lock=threading.Lock()
def lock(self):
self.lock.acquire()
def unlock(self):
self.lock.release()
def p2(a):
global num
thread.lock()
num+=1
print(a+num)
time.sleep(3)
thread.unlock()
def p1(a):
for i in range(3):
info='this %s thread'%(i)
p2(info)
def main():
for i in range(3):
p1(i)
if __name__ == '__main__':
thread=Thread()
main() 展开
2个回答
展开全部
下面的代码可以,因为你那个lock是变量又是函数,会冲突的,另外,你这个实验其实测试不出来lock属性,因为你调用实际上是顺序的
import string,socket,time,os,sys,threading
num=0
class xThread():
def __init__(self):
self._lock=threading.Lock()
def lock(self):
self._lock.acquire()
def unlock(self):
self._lock.release()
def p2(a):
global num
thread.lock()
num+=1
print(a+str(num))
time.sleep(0.1)
thread.unlock()
def p1(a):
for i in range(3):
info='this %s thread'%(i)
p2(info)
def main():
for i in range(3):
p1(i)
if __name__ == '__main__':
thread=xThread()
main()
import string,socket,time,os,sys,threading
num=0
class xThread():
def __init__(self):
self._lock=threading.Lock()
def lock(self):
self._lock.acquire()
def unlock(self):
self._lock.release()
def p2(a):
global num
thread.lock()
num+=1
print(a+str(num))
time.sleep(0.1)
thread.unlock()
def p1(a):
for i in range(3):
info='this %s thread'%(i)
p2(info)
def main():
for i in range(3):
p1(i)
if __name__ == '__main__':
thread=xThread()
main()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询