下面这段python的多线程代码为什么运行不起来,说是函数没有加锁的属性

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()

下面的代码可以,因为你那个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()
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答