简体   繁体   English

如何在 python 中退出线程

[英]How can I exit thread in python

Hi guy I am writing a socket programming in python and using multithreading but I have one problem when I want to exit a program It seem like I can not exit a running thread.嗨,我正在 python 中编写套接字编程并使用多线程,但是当我想退出程序时遇到一个问题似乎我无法退出正在运行的线程。

picture of my code我的代码图片

def create_workers():
for _ in range(NUMBER_OF_THREADS):
    t = threading.Thread(target=work)
    t.daemon = True  # End the Thread
    t.start()



def work():
    while True:

        x = queue.get()
        if x == 1:
            create_socket()
            bind_socket()
            accept_connections()
        if x == 2:
            start_turtle()
            break

        queue.task_done()

the function create_workers are running two thread and targeting function work but I don't really know to terminate it after I break a while loop in function work function create_workers 正在运行两个线程并针对 function 工作,但我真的不知道在 function 工作中打破 while 循环后终止它

Use a threading.Event instance as a flag that you set just before work ends, and check if it is set at the start of each iteration of the infinite loop.使用threading.Event实例作为您在work结束前设置的标志,并检查它是否在无限循环的每次迭代开始时设置。

If your work function is more complicated, with multiple return statements, you could chuck the event.set() call into the finally block of a try statement.如果您的work function 更复杂,有多个return语句,您可以将event.set()调用放入try语句的finally块中。

threading.Event is thread-safe. threading.Event是线程安全的。

As pointed out by user2357112 supports Monica , making the threads daemonic doesn't make sense, so I've removed that line.正如user2357112 所指出的支持 Monica ,使线程守护进程没有意义,所以我删除了该行。

def create_workers():
    event = threading.Event()
    for _ in range(NUMBER_OF_THREADS):
        t = threading.Thread(target=work, args=(event,))
        t.start()

def work(event):
    while True:
        if event.is_set():
            return
        
        x = queue.get()
        if x == 1:
            create_socket()
            bind_socket()
            accept_connections()
        if x == 2:
            start_turtle()
            break
        
        queue.task_done()
    
    event.set()

you can use python-worker ( link )你可以使用python-worker (链接)

from worker import abort_all_thread

## your running code

abort_all_thread() # this will kill any active threads

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM