有没有办法编写命令以中止正在运行的函数调用?
我有一个小部件可以测量经过的时间,然后在一定的持续时间后它会执行一个命令。但是,如果小部件被保留,我希望它中止此函数调用而不执行命令。
我该怎么办?
I have a widget that measures elapsed time, then after a certain duration it does a command. However, if the widget is left I want I want it to abort this function call and not do the command.
How do I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
threading
模块并启动一个将运行该函数的新线程。仅仅中止该函数是一个坏主意,因为您不知道是否在危急情况下中断线程。你应该像这样扩展你的函数:
Use the
threading
module and start a new thread that will run the function.Just abort the function is a bad idea as you don't know if you interrupt the thread in a critical situation. You should extend your function like this:
为什么不使用线程并停止它呢?我认为不可能在单线程程序中拦截函数调用(如果没有某种信号或中断)。
另外,对于您的具体问题,您可能需要引入一个标志并在命令中检查它。
Why not use threads and stop that? I don't think it's possible to intercept a function call in a single threaded program (if not with some kind of signal or interrupt).
Also, with your specific issue, you might want to introduce a flag and check that in the command.
不知道Python线程,但一般来说,中断线程的方式是通过拥有某种可以从小部件中设置的线程安全状态对象,以及线程代码中的逻辑来检查状态对象值的变化并中断脱离线程循环。
No idea about python threads, but in general the way you interrupt a thread is by having some sort of a threadsafe state object that you can set from the widget, and the logic in thread code to check for the change in state object value and break out of the thread loop.