python - 停止正在运行阻塞操作的线程

标签 python gps python-multithreading gpsd

我在停止正在执行阻塞操作的线程时遇到问题。我正在编写一个使用 gpsd 的程序,它是 python 绑定(bind),线程的 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 已修复,则代码工作正常。

非常感谢!

最佳答案

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

并且它工作正常。谢谢!

关于python - 停止正在运行阻塞操作的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17526902/

相关文章:

java - 如何判断Android上的行进方向?

Python:无法从外部进程设置进程变量

python - 如何停止守护线程?

python - 递归错误 : maximum recursion depth exceeded while using thread

python - 在字符串python中查找最长的唯一子字符串

python - 为什么我的代码会产生 TypeError : 'NoneType' object is not iterable

使用C语言转换GPS坐标单位

python - 将 GeoJSON 叠加层加载到 Folium 会引发 ValueError : Cannot render objects with any missing geometries

python - 如何断言类覆盖默认的 __hash__ 和 __eq__

android - 如何从我的应用程序的所有用户获取GPS坐标?