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

标签 python

是否有某种方法可以使用 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/

相关文章:

python - 如何从 Python 中的一组正则表达式匹配中提取第一个非空匹配?

python - 用于 scikit learn 的 SVM 轻型加载器

python - 从 ipywidgets.widgets.SelectMultiple 获取值

python - 如何使用 FOR/LIST/DICTIONARY 理解(不是 SQL)来使用 Python 左外连接?

python - python 文件上的随机选择不起作用

python - pyclustering 当矩阵具有三个以上的维度时可视化 xmeans

Python:打印变量的名称和值?

python - 在 Django 模板中通过变量访问字典?

python - 如何始终为使用 PyTest 测试的 Flask 应用程序提供上下文?

python - 使自定义类表现得像集合