4

我在停止执行阻塞操作的线程时遇到问题。我正在编写一个使用 gpsd 的程序,它是 python 绑定,线程的 run 方法如下所示:

def run(self):
    print "inside run. outside while"
    global gpsd
    while self.running:
        print "inside while"
        try:
            print "before next()"
            gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
            print "after next()"
            self.file_descriptor.write(str(int(time.time())) + ',' + str(gpsd.fix.latitude) + ',' + str(gpsd.fix.longitude) + ',' + str(gpsd.fix.altitude) + ',' + str(gpsd.fix.speed) + '\n')
            print "after write"
            #self.file_descriptor.write("self.running" + str(self.running) + '\n')
            self.file_descriptor.flush()
            print "after flush"
            time.sleep(5)
            print "after sleep"
        except:
            print "inside thread except"
            raise

问题是 next() 方法被阻塞了,所以即使我从我的主线程调用:

    print "Stopping GPS thread"
    gpsp.running = False
    gpsp.join() # wait for the thread to finish what it's doing

当没有 GPS 修复时,运行方法在 next() 上被阻止,不会自行停止......有什么想法吗?如果 GPS 已修复,则代码工作正常。

非常感谢!

4

2 回答 2

5

好吧,我想我做到了。gps 库有一个非阻塞方法来检查数据是否可用,所以现在它看起来像:

def run(self):
    global gpsd
    while self.running:
        try:
            if gpsd.waiting(): #only True if data is available
                gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer

            self.file_descriptor.write(str(int(time.time())) + ',' + str(gpsd.fix.latitude) + ',' + str(gpsd.fix.longitude) + ',' + str(gpsd.fix.altitude) + ',' + str(gpsd.fix.speed) + '\n')
            self.file_descriptor.flush()
            time.sleep(5)
        except:
            raise

它工作正常。谢谢!

于 2013-07-08T12:56:57.847 回答
0

我知道这不是很优雅,但这是我到目前为止所使用的代码,并且似乎工作正常。以防万一对任何人都有用。

它每 5 秒从 gpsd 读取 GPS 位置并将其写入文件。

while self.running:
                try:
                    if gpsd.waiting():
                        #print "inside waiting()"
                        while gpsd.waiting():
                            gpsd.next()          

                        self.file_descriptor.write(str(int(time.time())) + ',' 
                                                   + str(gpsd.fix.latitude) + ',' 
                                                   + str(gpsd.fix.longitude) + ',' 
                                                   + str(gpsd.fix.altitude) + ',' 
                                                   + str(gpsd.fix.speed) + '\n')
                        self.clear_fix()                
                    else:                    
                        self.file_descriptor.write(str(int(time.time())) + ",NO_GPS_FIX\n")

                    self.file_descriptor.flush()
                    time.sleep(5)
                except:
                    print "Exception on run()inside thread"
                    raise
于 2013-07-09T10:48:24.037 回答