- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有这个线程在后台运行,可以从主线程更新:
import threading
from Queue import Queue
from time import sleep
class Animation(threading.Thread):
SIGNAL_STOP = 'stop'
def __init__(self, framerate):
threading.Thread.__init__(self)
self.queue = Queue()
self.framerate = framerate
def tell(self, data):
self.queue.put(data)
def stop(self):
self.tell(Animation.SIGNAL_STOP)
def loop(self):
# Override this method to implement animation loop
pass
def update(self, data):
# Override this method to implement the state update
pass
def cleanup(self):
# Override this method to implement what's done when the animation is stopped
pass
def run(self):
while True:
if not self.queue.empty():
data = self.queue.get()
if data == Animation.SIGNAL_STOP:
break;
self.update(data)
self.loop()
sleep(1. / self.framerate)
self.cleanup()
class TestAnimation(Animation):
def __init__(self, framerate):
super(TestAnimation, self).__init__(framerate)
self.num = 0
def loop(self):
print 'num =', self.num
self.num = self.num + 1
def update(self, data):
print 'update:', data
def cleanup(self):
print 'graceful exit'
print 'start'
ta = TestAnimation(1)
ta.start()
sleep(3)
ta.update(123)
sleep(3)
#ta.stop() # I'd like the animation thread to feel that the parent wants to exit and carry out stopping itself
print 'end'
exit()
我想实现一些方法来检测父线程何时要退出,然后所有正在运行的线程都会自行终止。我更喜欢这样,而不是显式调用正在运行的线程的 stop() 方法。
最佳答案
我相信你可以将其设为 daemon thread,所以当主线程退出时,所有守护线程都会随之退出。
因此您可以在构造函数中默认为 daemon = True
或在 start
之前设置它
ta = TestAnimation(1)
ta.daemon = True
ta.start()
您可以使用 thread.Event
的组合和 atexit
用于向守护进程线程发出信号以在退出前进行清理。
这是一个简单的例子:
import time
import threading
import atexit
signal_to_threads = threading.Event() # Global signal for threads to stop.
registered_threads = [] # Register all threads into here.
@atexit.register
def signal_threads():
print('signaling threads to stop')
signal_to_threads.set()
for thread in registered_threads:
thread.signal.wait()
class TestExit(threading.Thread):
def __init__(self, *args, **kw):
registered_threads.append(self)
self.signal = threading.Event()
super(TestExit, self).__init__(*args, **kw)
self.daemon = True # Ensure is a daemon thread.
def run(self):
while True:
time.sleep(3)
print('Hi from child thread')
if signal_to_threads.is_set():
print('stopping child thread and doing cleanup.')
# self.do_cleanup()
self.signal.set()
break
t = TestExit()
t.start()
print('sleeping for 10 secs.')
time.sleep(10)
print('exiting main thread')
python test_thread.py
sleeping for 10 secs.
Hi from child thread
Hi from child thread
Hi from child thread
exiting main thread
signaling threads to stop
Hi from child thread
stopping child thread and doing clean up.
因为 atexit
应该在退出时运行注册的函数,所以不需要跟上每个退出点来清理线程。
关于Python:检测父线程是否调用了exit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54394188/
我相信所有这些(甚至是 die() 或 die(0))都是相同的。如果它们不相同,那么哪个更适合成功退出脚本?如果它们相同,是否有任何首选标准表明脚本成功完成?我倾向于使用 exit;. 编辑:所有答
我想知道Java中以下之间的区别 System.exit(0);System.exit(-1);System.exit(1); 我什么时候必须适本地使用上面的代码?
我注意到 Powershell 中有一个奇怪的行为。有两个 .ps1 文件: main.ps1: echo "running exit.ps1" $myexitcode = & ".\exit.p
Anylogic Process Modeling Library 中很少有像“Source”这样的 block 具有“On exit”和“On at exit”这样的操作。两者有什么区别? 我试图创
所以我有这个 Bash 脚本: #!/bin/bash PID=`ps -u ...` if [ "$PID" = "" ]; then echo $(date) Server off: no
(gdb) info symbol exit exit in section .text of /lib64/libc.so.6 (gdb) info symbol _exit _exit in se
如果我想启动一个简单的应用程序,几周前我使用它没有出现错误,我会收到错误消息。那是他的错误描述: Launching lib\main.dart on SM J530F in debug mode..
这个问题已经有答案了: Using Platform.exit() and System.exit(int) together (3 个回答) 已关闭 5 年前。 这里有人建议使用后者。我是java新
我的理解是,在 bash 中,一个普通的 exit 将完成一个具有最后一个命令的退出状态的脚本。但我也看到有人使用 exit $? 并且当我建议它具有相同的行为时被质疑。 这两个脚本之间有什么有意义的
我看到一些代码是这样做的: if(something){ echo 'exit from program'; die; } ...more code 和其他只使用 die 的人: if
exit和exit有什么区别!在 ruby 中? 最佳答案 一些事情: 退出处理程序以“退出”形式而非“退出!”形式运行。这意味着分配给“清理”的任何代码都不会使用“退出!”运行 “退出状态”在“退出
我们有一堆 .bat构建脚本由基于 PowerShell 的 GitLab 运行程序调用,这些脚本最近从以下内容重构: program args if !errorlevel! neq 0 exit
我想关闭具有指定返回码的 javafx 应用程序。浏览 SO 上的答案,我发现了以下成语: Platform.exit(); System.exit(0); 例如这里: Stop threads be
exit 和 C++ 中的 std::exit 有什么区别?我已经对其进行了研究,但我找不到任何东西。 这两个代码有什么区别: 1: if(SDL_Init(SDL_INIT_EVERYTHING)
我需要一个替代方法来在线程函数内终止 python 脚本。我的意图是在客户端输入 0 时终止服务器...这是否不起作用,因为线程尚未终止?这是我的代码: socket = socket.socket(
我想在崩溃后重新启动应用程序。我正在使用下面的代码来执行该任务。 Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen
在Delphi中,你可以退出一个函数并给它一个返回值,这与C/C++/Java/C#等中的return关键字非常相似 Exit(1); 但是,我通常会写这样的内容: Result := 1; Exit
我想知道是否有任何方法可以处理浏览器退出事件。 例如,我想在用户单击交叉退出或关闭浏览器时发送查询。 最佳答案 我想我已经找到了解决办法。我没有在 IE 上测试过它,但它似乎在 Firefox 上运行
我在 Archlinux 的 mkinitcpio 脚本中找到了以下代码片段。 cleanup() { if [[ $workdir ]]; then # when PRESE
我使用以下代码计算数据帧所有行之间的余弦相似度: from pyspark.ml.feature import Normalizer from pyspark.mllib.linalg.distrib
我是一名优秀的程序员,十分优秀!