我在停止执行阻塞操作的线程时遇到问题。我正在编写一个使用 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 已修复,则代码工作正常。
非常感谢!