我需要实现这样的东西
def turnOn(self):
self.isTurnedOn = True
while self.isTurnedOn:
updateThread = threading.Thread(target=self.updateNeighborsList, args=())
updateThread.daemon = True
updateThread.start()
time.sleep(1)
def updateNeighborsList(self):
self.neighbors=[]
for candidate in points:
distance = math.sqrt((candidate.X-self.X)**2 + (candidate.Y-self.Y)**2)
if distance <= maxDistance and candidate!=self and candidate.isTurnedOn:
self.neighbors.append(candidate)
print self.neighbors
print points
这是一个类成员函数,在self.isTurnedOn == True
之前,应该每隔一秒从中调用updateNeighborsList
函数。
当我创建class对象并调用turnOn
函数时,下面的所有语句都没有被执行,它在while循环上进行控制和堆栈,但是我需要很多class对象。
做这种事的正确方法是什么?你知道吗
我认为最好在调用
turnOn
时创建一个Thread
,并在该线程内执行循环:不过,请注意,由于全局解释器锁的存在,在线程内部进行数学计算并不能提高使用CPython的性能。为了并行使用多个内核,您需要使用^{} 模块。但是,如果您只是想防止主线程阻塞,请随意使用线程。只需知道一次只有一个线程在运行。你知道吗
相关问题 更多 >
编程相关推荐