gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:32:21 28 4
gpt4 key购买 nike

我在停止正在执行阻塞操作的线程时遇到问题。我正在编写一个使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com