问题描述
在下面的代码中,我正在学习如何同步线程。我参考了几个教程。如教程中所述,我必须使用 Lock() 对象才能调用
.acquire() and .release()
我编写了以下代码,但总是收到以下错误: 请告诉我如何正确同步线程
self._target(*self._args,**self._kwargs)
File "m:\python lessons\ThreadsWithSync.py",line 42,in isNumPrime
lock.acquire()
NameError: name 'lock' is not defined
lock.acquire()
lock.acquire()
NameError: name 'lock' is not defined
代码:
import threading
from threading import Lock,Thread
import logging
import time
from random import seed
from random import randint
class ThreadsWithSync(threading.Thread):
lock = Lock()
def __new__(cls):
"""
For object creation
"""
print("cls: %s"%(cls))
#cls.onCreateObject()
instance = super(ThreadsWithSync,cls).__new__(cls)
#print("instace: %s"%(instance.__repr__)) #activate this line whenever an @R_850_4045@ive and descriprtive text about the instance is needed to be displayed
return instance
def __init__(self):
"""
For object initialization
"""
#print("self: %s"%(self))
threading.Thread.__init__(self) #to initialize the super class
print("self: %s"%(self))
#seed(.1) #when set to integer number,the randomly generated numbers will be the same. ommit this to get different random numbers each run.
@classmethod
def onCreateObject(cls):
"""
This will be invoked once the creation procedure of the object begins.
"""
def __repr__(self):
"""
similar to toString in Java
"""
return "\n__class__: " + repr(self.__class__) +"\n__new__:" + repr(self.__new__) + "\n__str__: " + repr(self.__str__) + "\n__sizeof__: " + repr(self.__sizeof__)
def isNumPrime(self,targetNum):
lock.acquire()
if targetNum == 0 or targetNum == 1:
print("thread name: %s targetNum passed to method,will return false: %s"%(threading.current_thread().name,targetNum))
return False
if targetNum == 2:
print("targetNum passed to method will return true: %s"%(targetNum))
return True
isPrim = True
for i in range(3,targetNum):
#print("thread name: %s in loop: targetNum: %s"%(threading.current_thread().name,targetNum))
if targetNum % i == 0:
isPrim = False
break
print("%s-> is %s a prime : %s"%(threading.current_thread().name,targetNum,isPrim))
return isPrim
def spawnThread(self):
if __name__ == "__main__":
self.main()
def main(self):
while True:
thread_1 = threading.Thread(group = None,target = self.isNumPrime,name='Thread_1',args = (),kwargs=dict(targetNum=randint(0,100)),daemon = None)
thread_2 = threading.Thread(group = None,name='Thread_2',daemon = None)
thread_3 = threading.Thread(group = None,name='Thread_3',daemon = None)
thread_4 = threading.Thread(group = None,name='Thread_4',daemon = None)
thread_1.start()
thread_2.start()
thread_3.start()
thread_4.start()
time.sleep(3)
t1 = ThreadsWithSync()
t1.spawnThread()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)