Python:如何停止正在等待.recv()的线程 [英] Python : how to stop a thread that's waiting for a .recv()

查看:366
本文介绍了Python:如何停止正在等待.recv()的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行该线程:

def run(self):
    while 1:
        msg = self.connection.recv(1024).decode()

我希望这样关闭Tkinter窗口时可以结束该线程:

self.window.protocol('WM_DELETE_WINDOW', self.closeThreads)

def closeThreads(self):
    self.game.destroy()
    #End the thread

不能使用thread._close(),因为它已被弃用,而python 3.4不允许使用.

解决方案

两种解决方案:

1)不要停止线程,仅当进程以sys.exit()退出时允许它死亡

2)使用立即死亡"标志启动线程. Event类专门用于从另一个线程发出信号.

下面的示例启动一个线程,该线程连接到服务器.任何数据都将被处理,并且如果父级发出信号退出线程,它将进行处理.作为附加的安全功能,我们提供了一个警报信号,可以杀死所有东西,以防万一某些东西失控.

import signal, socket, threading

class MyThread(threading.Thread):
    def __init__(self, conn, event):
        super(MyThread,self).__init__()
        self.conn = conn
        self.event = event

    def handle_data(self):
        "process data if any"
        try:
            data = self.conn.recv(4096)
            if data:
                print 'data:',data,len(data)
        except socket.timeout:
            print '(timeout)'

    def run(self):
        self.conn.settimeout(1.0)
        # exit on signal from caller
        while not self.event.is_set():
            # handle any data; continue loop after 1 second
            self.handle_data()
        print 'got event; returning to caller'


sock = socket.create_connection( ('example.com', 80) )
event = threading.Event()

# connect to server and start connection handler
th = MyThread(conn=sock, event=event)

# watchdog: kill everything in 3 seconds
signal.alarm(3)

# after 2 seconds, tell data thread to exit 
threading.Timer(2.0, event.set).start()

# start data thread and wait for it
th.start()
th.join()

输出

(timeout)
(timeout)
got event; returning to caller

I have this thread running :

def run(self):
    while 1:
        msg = self.connection.recv(1024).decode()

I wish I could end this thread when I close the Tkinter Window like this :

self.window.protocol('WM_DELETE_WINDOW', self.closeThreads)

def closeThreads(self):
    self.game.destroy()
    #End the thread

Can't use thread._close() because it is deprecated and python 3.4 does not allow it.

解决方案

Two solutions:

1) Don't stop the thread, just allow it to die when the process exits with sys.exit()

2) Start the thread with a "die now" flag. The Event class is specifically designed to signal one thread from another.

The following example starts a thread, which connects to a server. Any data is handled, and if the parent signals the thread to exit, it will. As an additional safety feature we have an alarm signal to kill everything, just it case something gets out of hand.

source

import signal, socket, threading

class MyThread(threading.Thread):
    def __init__(self, conn, event):
        super(MyThread,self).__init__()
        self.conn = conn
        self.event = event

    def handle_data(self):
        "process data if any"
        try:
            data = self.conn.recv(4096)
            if data:
                print 'data:',data,len(data)
        except socket.timeout:
            print '(timeout)'

    def run(self):
        self.conn.settimeout(1.0)
        # exit on signal from caller
        while not self.event.is_set():
            # handle any data; continue loop after 1 second
            self.handle_data()
        print 'got event; returning to caller'


sock = socket.create_connection( ('example.com', 80) )
event = threading.Event()

# connect to server and start connection handler
th = MyThread(conn=sock, event=event)

# watchdog: kill everything in 3 seconds
signal.alarm(3)

# after 2 seconds, tell data thread to exit 
threading.Timer(2.0, event.set).start()

# start data thread and wait for it
th.start()
th.join()

output

(timeout)
(timeout)
got event; returning to caller

这篇关于Python:如何停止正在等待.recv()的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆