0

我正在从加速度计捕获数据。我希望用户能够通过分别按下开始和停止按钮来开始记录数据和停止记录。我决定使用线程来执行此操作,因此开始按钮创建一个捕获数据的线程,而停止按钮停止该线程并获取记录的数据。

我遇到的问题是,要么没有记录数据,要么按下停止按钮时,线程没有结束,而是在几秒钟到几分钟的任何时间里记录数据。

我现在正在做的是线程运行一个循环来记录数据并检查变量是否设置为 True,如果是,则循环应该结束。我还有一个 end() 函数,该函数旨在从主线程调用,并且假设将变量设置为 True 以结束线程。

class Capture(Thread):
def __init__(self,accel):
    Thread.__init__(self)
    self.accel=accel
    self.ended=False
    self.data=[]
    self.lock=Lock()

def run(self):
    while self.isEnded()==False:
        self.lock.acquire()
        self.data.append(self.accel.read())
        self.lock.release()

def getData(self):
    self.lock.acquire()
    d=self.data
    self.data=[]
    self.lock.release()
    return d

def isEnded(self):
    self.lock.acquire()
    end=self.ended
    self.lock.release()
    return end

def end(self):
    self.lock.acquire()
    self.ended=True
    self.lock.release()
4

1 回答 1

0

I'm afraid I don't know python very well at all but I'll take a guess. If accel.read() calls out to some external code (eg a device driver) and blocks for a second then the python interpreter is also blocked. No other thread will run. When the read finally returns you release the lock. At this point the interpreter is going to have to decide what to do next, and your thread merely loops, takes the lock again and goes back to reading (and being blocked)

So I'm guessing that you're falling foul of interpreter lock, and that there's an element of blind luck involved in whether your main thread gets run at all, in which case your stop button handling doesn't happen.

Could that be it?

于 2013-04-04T18:31:36.897 回答