python类成员函数中的无限循环。线程?

2024-10-02 12:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要实现这样的东西

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对象。 做这种事的正确方法是什么?你知道吗


Tags: and函数selftruedefneighborscandidatepoints
1条回答
网友
1楼 · 发布于 2024-10-02 12:27:58

我认为最好在调用turnOn时创建一个Thread,并在该线程内执行循环:

def turnOn(self):
    self.isTurnedOn = True
    self.updateThread = threading.Thread(target=self.updateNeighborsList, args=())
    self.updateThread.daemon = True
    self.updateThread.start()

def updateNeighborsList(self):
    while self.isTurnedOn:
        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
        time.sleep(1)

不过,请注意,由于全局解释器锁的存在,在线程内部进行数学计算并不能提高使用CPython的性能。为了并行使用多个内核,您需要使用^{}模块。但是,如果您只是想防止主线程阻塞,请随意使用线程。只需知道一次只有一个线程在运行。你知道吗

相关问题 更多 >

    热门问题