简体   繁体   English

终止在 python 中等待的线程

[英]Terminating thread thats waiting in python

I am trying to learn how to use threading with networking and need to stop a thread if a connection is closed.我正在尝试学习如何在网络中使用线程,并且如果连接关闭,则需要停止线程。 I have a list of multiple connections and a thread that checks if they are still open.我有一个多个连接的列表和一个检查它们是否仍然打开的线程。

If a connection has closed i need to terminate the GetData() thread but i don't know how to do that without checking for an exit event every loop.如果连接已关闭,我需要终止 GetData() 线程,但如果不检查每个循环的退出事件,我不知道该怎么做。 The problem is that the GetData() thread doesn't loop but sits at line 25 and waits for a response.问题是 GetData() 线程没有循环,而是位于第 25 行并等待响应。 If the connection has closed it never gets a response and just keeps sitting there until i kill the program.如果连接已关闭,它永远不会得到响应,只会一直坐在那里,直到我终止程序。

How do i kill a thread outside of the thread.我如何杀死线程外的线程。 I understand that this is not easily done with threading but is there maybe some other library that allows this?我知道这不是通过线程轻松完成的,但是否有其他库允许这样做? I also tried using multiprocessing instead but i couldn't get it to work so i just gave up on that.我也尝试使用多处理,但我无法让它工作,所以我放弃了。

from threading import Thread
import socket

def MakeSocket():
    try:
        global MainSocket
        MainSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
        print ("Socket successfully created") 
    except socket.error as err:  
        print ("socket creation failed with error %s" %(err)) 
    MainSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    MainSocket.bind(('', 1337))
    MainSocket.listen(5)

    global c
    global addr
    c, addr = MainSocket.accept()
    Thread(target=GetData, args=()).start()
    Thread(target=CheckIfOpen, args=()).start()

def GetData():
    while True:
        try:
            #Try to recieve data from connection.
            RecievedData = c.recv(4096).decode()
            print(RecievedData)
        except:
            print ("\nError: GetData failed.\n")
            return

def CheckIfOpen():
    while True:
        #wait 5 sec between each test
        time.sleep(5)
        try:
            #try to send data "test".
            c.send("test".encode())
        except:
            #if it fails then the connection has been closed. Close the GetData thread
            #Don't know how to close the GetData thread

MakeSocket()

I know this looks silly but it isn't all my code.我知道这看起来很傻,但这并不是我的全部代码。 I just changed it a bit and included the important parts.我只是对其进行了一些更改,并包括了重要的部分。 It still contains the same problem.它仍然包含相同的问题。 I don't have all those global variables in my actual code.我的实际代码中没有所有这些全局变量。

I realized what was wrong.我意识到出了什么问题。 https://reddit.com/r/learnpython/comments/kx925z/terminating_thread_thats_waiting/ https://reddit.com/r/learnpython/comments/kx925z/terminating_thread_thats_waiting/

u/oefd pointed something i missed out in the comments. u/oefd 指出了我在评论中遗漏的一些东西。

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

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