Python:有没有办法检查“是否请求停止”?在线程中的每一行之前?

发布于 2025-01-14 18:28:23 字数 614 浏览 4 评论 0原文

我希望能够同时中断多个线程。一种解决方案可能是:

stop_all_threads = False

def abort_if_requested():
    global stop_all_threads

    if stop_all_threads:
        raise Exception()


def thread_target():
    abort_if_requested()
    do_some_work()
    abort_if_requested()
    do_more_work()
    abort_if_requested()
    last_work_piece()


my_thread = threading.Thread(target=thread_target)
my_thread.start()

...

stop_all_threads = True

但显然,遵循起来有点烦人,并且如果工作功能需要很长时间,也不会立即停止它们。有没有更简单的方法?我知道 multiprocessing.Process.terminate 但我必须在我的用例中使用 threading.Thread,或者其他提供低延迟共享内存的方法。

I want to be able to interrupt many threads at once. One solution could be:

stop_all_threads = False

def abort_if_requested():
    global stop_all_threads

    if stop_all_threads:
        raise Exception()


def thread_target():
    abort_if_requested()
    do_some_work()
    abort_if_requested()
    do_more_work()
    abort_if_requested()
    last_work_piece()


my_thread = threading.Thread(target=thread_target)
my_thread.start()

...

stop_all_threads = True

But obviously it's a bit annoying to follow and doesn't stop them immediately if the work functions take long. Is there a simpler way? I know about multiprocessing.Process.terminate but I have to use threading.Thread in my use case, or some other method that provides shared memory with low latency.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

琉璃梦幻 2025-01-21 18:28:23

我不太确定你在这里问什么,但这是我唯一能想到的:

stop_all_threads = False

def abort_if_requested():
    global stop_all_threads
    
    if stop_all_threads:
        raise Exception()

def thread_target():
    def check():
        while True:
            abort_if_requested()
            time.sleep(0.75)
    checkThread = threading.Thread(target=check)
    checkThread.start()
    do_some_work()

尝试重新编码,因为我不太明白你在这里需要什么。

I'm not too sure what you're asking here but this is the only thing I can think of:

stop_all_threads = False

def abort_if_requested():
    global stop_all_threads
    
    if stop_all_threads:
        raise Exception()

def thread_target():
    def check():
        while True:
            abort_if_requested()
            time.sleep(0.75)
    checkThread = threading.Thread(target=check)
    checkThread.start()
    do_some_work()

Try to recode this because I don't really understand what you needed here.

他是夢罘是命 2025-01-21 18:28:23

您可以传递 Event来自 threading 库的类作为线程目标函数的参数,并在您想要停止所有线程上的处理时设置它。当事件被设置时,while 循环将停止,线程将正常终止。

我还建议您通过调用 < 等待线程终止Thread 对象上的 code>join 方法。如果您需要处理结果,这可以确保结果可用并且线程终止。如果您使用多个线程,请对所有线程调用join

from threading import Thread, Event

def do_work_1(args):
    # Do your work here

def do_work_2(args):
    # Do your work here

def thread_target(stop_event, funcs, funcs_args):
    # Perform work until the event is set
    for idx, func in enumerate(funcs):
        func(funcs_args[idx])
        if stop_event.is_set():
           break

stop_event = Event()

sequential_work_funcs = [do_work_1, do_work_2, do_work_2]
# Add arguments you want to pass to functions 
# (args on the index get passed to func of same index)
sequential_work_funcs_args = [{}, {}, {}] 

# Pass the event as an argument to the target function
my_thread = Thread(target=thread_target, args=(stop_event, sequential_work_funcs, sequential_work_funcs_args))
my_thread.start()

# When you want to stop the threads
stop_event.set()

# Wait for thread to gracefully terminate if you need results of work
# join() is a blocking call that returns when the thread terminates
my_thread.join()

You can pass the Event class from threading library as an argument to the thread target function and set it when you want to stop processing on all threads. When the event will be set, while loops will stop and the thread will gracefully terminate.

I also suggest you to wait for the thread to terminate by calling join method on your Thread object. If you need the results from your processing, this ensures that the results are available and the thread terminated. If you're using multiple threads, call join on all of them.

from threading import Thread, Event

def do_work_1(args):
    # Do your work here

def do_work_2(args):
    # Do your work here

def thread_target(stop_event, funcs, funcs_args):
    # Perform work until the event is set
    for idx, func in enumerate(funcs):
        func(funcs_args[idx])
        if stop_event.is_set():
           break

stop_event = Event()

sequential_work_funcs = [do_work_1, do_work_2, do_work_2]
# Add arguments you want to pass to functions 
# (args on the index get passed to func of same index)
sequential_work_funcs_args = [{}, {}, {}] 

# Pass the event as an argument to the target function
my_thread = Thread(target=thread_target, args=(stop_event, sequential_work_funcs, sequential_work_funcs_args))
my_thread.start()

# When you want to stop the threads
stop_event.set()

# Wait for thread to gracefully terminate if you need results of work
# join() is a blocking call that returns when the thread terminates
my_thread.join()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文