有没有办法编写命令以中止正在运行的函数调用?

发布于 2024-09-16 13:32:10 字数 89 浏览 4 评论 0原文

我有一个小部件可以测量经过的时间,然后在一定的持续时间后它会执行一个命令。但是,如果小部件被保留,我希望它中止此函数调用而不执行命令。

我该怎么办?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦罢 2024-09-23 13:32:10

使用threading模块并启动一个将运行该函数的新线程。

仅仅中止该函数是一个坏主意,因为您不知道是否在危急情况下中断线程。你应该像这样扩展你的函数:

import threading

class WidgetThread(threading.Thread):
     def __init__(self):
         threading.Thread.__init__(self)
         self._stop = False

     def run(self):
        # ... do some time-intensive stuff that stops if self._stop ...
        #
        # Example:
        #  while not self._stop:
        #      do_somthing()

     def stop(self):
         self._stop = True



# Start the thread and make it run the function:

thread = WidgetThread()
thread.start()

# If you want to abort it:

thread.stop()

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:

import threading

class WidgetThread(threading.Thread):
     def __init__(self):
         threading.Thread.__init__(self)
         self._stop = False

     def run(self):
        # ... do some time-intensive stuff that stops if self._stop ...
        #
        # Example:
        #  while not self._stop:
        #      do_somthing()

     def stop(self):
         self._stop = True



# Start the thread and make it run the function:

thread = WidgetThread()
thread.start()

# If you want to abort it:

thread.stop()
栖迟 2024-09-23 13:32:10

为什么不使用线程并停止它呢?我认为不可能在单线程程序中拦截函数调用(如果没有某种信号或中断)。

另外,对于您的具体问题,您可能需要引入一个标志并在命令中检查它。

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.

倦话 2024-09-23 13:32:10

不知道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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文