停止运行阻塞操作的线程

时间:2013-07-08 12:41:32

标签: python gps python-multithreading gpsd

我在停止正在执行阻塞操作的线程时遇到问题。我正在编写一个使用gpsd并且它是python绑定的程序,Thread的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修复时,run方法被阻止在next()上不会自行停止......任何想法?如果GPS已经修复,代码工作正常。

非常感谢!

2 个答案:

答案 0 :(得分:4)

好的,我想我做到了。 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

它运作正常。谢谢!

答案 1 :(得分:0)

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

它正在从gpsd读取GPS位置并每隔5秒将其写入一个文件。

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