gpt4 book ai didi

python - 有类似于微 Controller 中断处理程序的东西吗?

转载 作者:行者123 更新时间:2023-11-30 23:49:48 25 4
gpt4 key购买 nike

是否有某种方法可以使用 try 语句来捕获由 raise 语句引起的错误,执行代码来处理该标志,例如更新一些变量,然后返回到标志被提升时代码正在运行的行?

我正在专门考虑微 Controller 的中断处理程序(它执行我刚才描述的操作)。

我正在编写一些代码,其中有一个线程检查文件以查看它是否更新,并且我希望它中断主程序,以便它知道更新,适本地处理它,并返回到它正在运行的行当被打断时。

理想情况下,主程序会识别线程中的标志,无论它在哪里执行。 try 语句可以做到这一点,但我如何返回到引发标志的行?

谢谢!保罗

编辑:

我在评论后尝试 ISR,尽管它看起来像是一个使用锁的非常直接的示例。底部的小测试例程用于演示代码

    import os
import threading
import time

def isr(path, interrupt):
prev_mod = os.stat(path).st_mtime
while(1):
new_mod = os.stat(path).st_mtime
if new_mod != prev_mod:
print "Updates! Waiting to begin"
# Prevent enter into critical code and updating
# While the critical code is running.
with interrupt:
print "Starting updates"
prev_mod = new_mod
print "Fished updating"
else:
print "No updates"
time.sleep(1)

def func2(interrupt):
while(1):
with interrupt: # Prevent updates while running critical code
# Execute critical code
print "Running Crit Code"
time.sleep(5)
print "Finished Crit Code"
# Do other things

interrupt = threading.Lock()

path = "testfil.txt"
t1 = threading.Thread(target = isr, args = (path, interrupt))
t2 = threading.Thread(target = func2, args = (interrupt,))
t1.start()
t2.start()

# Create and "Update" to the file
time.sleep(12)
chngfile = open("testfil.txt","w")
chngfile.write("changing the file")
chngfile.close()
time.sleep(10)

最佳答案

处理中断的一种标准操作系统方法是将中断排队,以便另一个内核线程可以处理它。

这部分适用于 Python。

I am writing some code that has a thread checking a file to see if it updates and I want it to interrupt the main program so it is aware of the update, deals with it appropriately, and returns to the line it was running when interrupted.

您有多个线程。您不需要“中断”主程序。只需在单独的线程中“适本地处理它”即可。当其他线程“适当处理”时,主线程将找到更新。

这就是我们有锁的原因。确保共享状态正确更新。

您可以通过锁定线程所需的资源来中断线程。

您可以通过获取资源锁来使线程可中断。

关于python - 有类似于微 Controller 中断处理程序的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7502483/

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