python run没了_如何在run方法中终止没有循环的Python线程?

Having class which has a long method.

Creating a thread for that method.

How i can kill\terminate this thread?

Main problem is that i can't check for threading.Event in thread run() method because it doesn't contain loop.

Similar code as here:

import time

import threading

class LongAction:

def time_consuming_action(self):

tmax = 600

for i in range(tmax):

print i

time.sleep(1)

time.sleep(tmax)

self.tmax = tmax

return "Slept well"

class LongActionThread(threading.Thread):

def __init__(self, la_object):

self.la = la_object

threading.Thread.__init__(self)

def run(self):

self.la.time_consuming_action()

la = LongAction()

la_thread = LongActionThread(la)

la_thread.start()

# After 5 sec i've changed my mind and trying to kill LongActionThread

time.sleep(5)

print "Trying to kill LongActionThread"

la_thread.kill()

解决方案

This code works fine but there is a need to explicitly flush data from standard output.

Haven't found a way where prints would work without flushing.

import time

from multiprocessing.process import Process

import sys

class LongAction:

def time_consuming_action(self):

tmax = 600

for i in range(tmax):

print i

time.sleep(1)

sys.stdout.flush()

time.sleep(tmax)

self.tmax = tmax

return "Slept well"

sys.stdout.flush()

class LongActionThread(Process):

def __init__(self, la_object):

self.la = la_object

Process.__init__(self)

def run(self):

self.la.time_consuming_action()

if __name__ == "__main__":

la = LongAction()

la_thread = LongActionThread(la)

la_thread.start()

# After 5 sec i've changed my mind and trying to kill LongActionThread

time.sleep(5)

print "Trying to kill LongActionThread"

la_thread.terminate()

### 回答1: 可以使用一个标志变量来控制循环是否继续执行,然后在需要终止线程时将标志变量设置为False。线程可以在每次循环迭代的末尾检查该标志变量的值,如果为False,则终止循环。 示例代码: ```python import threading class MyThread(threading.Thread): def __init__(self): super().__init__() self._stop_event = threading.Event() def run(self): while not self._stop_event.is_set(): # 你的循环代码 def stop(self): self._stop_event.set() ``` 在需要终止线程的地方调用`stop()`方法即可。注意要在所有线程终止之后再退出程序,否则可能会导致未预期的行为。 ### 回答2: 在Python,要在线程循环终止它,可以使用多线程模块的`Thread`类和一个标志位来实现。以下是一个示例代码: ```python import threading # 定义一个标志位来控制线程是否继续执行 stop_flag = False def my_thread_function(): global stop_flag while not stop_flag: # 线程循环逻辑 # ... # 创建并启动线程 my_thread = threading.Thread(target=my_thread_function) my_thread.start() # 主线程根据条件来终止线程 if 某个条件: stop_flag = True # 等待线程执行完毕 my_thread.join() ``` 在上面的代码,我们首先定义了一个标志位`stop_flag`,它用来控制线程是否继续执行循环逻辑。在线程循环,我们通过检查`stop_flag`的值来判断是否需要终止线程。当满足某个条件时,主线程将`stop_flag`设置为`True`,从而通知子线程停止循环。最后,主线程使用`join()`方法等待子线程执行完毕。 这种方法可以实现线程循环终止,但需要注意的是,在循环逻辑要定期检查`stop_flag`的值,以便及时响应终止请求。另外,如果循环逻辑存在长时间的阻塞操作(例如IO操作),需要在合适的地方添加额外的检查点来确保能够及时退出循环。 ### 回答3: 在线程运行的过程,可以使用以下几种方式来终止线程: 1. 使用全局变量进行控制:在循环,设置一个全局变量作为结束标志,当满足某个条件时,将该标志设为True,使线程退出循环终止。 ```python import threading # 作为结束标志的全局变量 stop_flag = False def my_thread(): global stop_flag while not stop_flag: # 线程的具体操作 # 创建并启动线程 t = threading.Thread(target=my_thread) t.start() # 在循环终止线程 stop_flag = True ``` 2. 使用`threading.Event`进行控制:`Event`是一个线程同步工具,可以用来在多个线程之间传递信号。通过设置`Event`的状态,来控制线程的运行状态。 ```python import threading # 创建一个事件对象 stop_event = threading.Event() def my_thread(): while not stop_event.is_set(): # 线程的具体操作 # 创建并启动线程 t = threading.Thread(target=my_thread) t.start() # 在循环终止线程 stop_event.set() ``` 3. 使用`threading.Thread`的`terminate()`方法:不推荐使用,因为该方法会强制终止线程,可能会导致资源无法正常释放,引发意外的问题。 ```python import threading def my_thread(): while True: # 线程的具体操作 # 创建并启动线程 t = threading.Thread(target=my_thread) t.start() # 在循环终止线程 t.terminate() ``` 总的来说,推荐使用全局变量或`threading.Event`来控制线程终止,在满足条件时,线程会自动退出循环终止
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值