[英]Is there any way to kill a Thread?
是否可以在不设置/检查任何标志/信号量/等的情况下终止正在运行的线程?
在 Python 和任何语言中,突然终止线程通常是一种糟糕的模式。 考虑以下情况:
如果您负担得起(如果您正在管理自己的线程),处理这个问题的好方法是拥有一个 exit_request 标志,每个线程定期检查该标志以查看是否该退出。
例如:
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
在这段代码中,当您希望线程退出时,您应该在线程上调用stop()
,并使用join()
等待线程正确退出。 线程应定期检查停止标志。
但是,在某些情况下,您确实需要终止线程。 一个例子是当你包装一个忙于长时间呼叫的外部库时,你想中断它。
以下代码允许(有一些限制)在 Python 线程中引发异常:
def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# "if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class ThreadWithExc(threading.Thread):
'''A thread class that supports raising an exception in the thread from
another thread.
'''
def _get_my_tid(self):
"""determines this (self's) thread id
CAREFUL: this function is executed in the context of the caller
thread, to get the identity of the thread represented by this
instance.
"""
if not self.isAlive():
raise threading.ThreadError("the thread is not active")
# do we have it cached?
if hasattr(self, "_thread_id"):
return self._thread_id
# no, look for it in the _active dict
for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid
# TODO: in python 2.6, there's a simpler way to do: self.ident
raise AssertionError("could not determine the thread's id")
def raiseExc(self, exctype):
"""Raises the given exception type in the context of this thread.
If the thread is busy in a system call (time.sleep(),
socket.accept(), ...), the exception is simply ignored.
If you are sure that your exception should terminate the thread,
one way to ensure that it works is:
t = ThreadWithExc( ... )
...
t.raiseExc( SomeException )
while t.isAlive():
time.sleep( 0.1 )
t.raiseExc( SomeException )
If the exception is to be caught by the thread, you need a way to
check that your thread has caught it.
CAREFUL: this function is executed in the context of the
caller thread, to raise an exception in the context of the
thread represented by this instance.
"""
_async_raise( self._get_my_tid(), exctype )
(基于 Tomer Filiba 的Killable Threads 。关于PyThreadState_SetAsyncExc
返回值的PyThreadState_SetAsyncExc
似乎来自旧版本的 Python 。)
正如文档中所指出的,这不是灵丹妙药,因为如果线程在 Python 解释器之外很忙,它就不会捕获中断。
这段代码的一个很好的使用模式是让线程捕获特定的异常并执行清理。 这样,您可以中断任务并仍然进行适当的清理。
一个multiprocessing.Process
可以p.terminate()
在我想杀死一个线程但不想使用标志/锁/信号/信号量/事件/任何东西的情况下,我将线程提升为完整的进程。 对于仅使用几个线程的代码,开销还不错。
例如,这有助于轻松终止执行阻塞 I/O 的助手“线程”
转换很简单:在相关的代码替换所有threading.Thread
与multiprocessing.Process
和所有queue.Queue
与multiprocessing.Queue
并添加所需的通话p.terminate()
到要杀死其子你的父进程p
请参阅Python 文档了解multiprocessing
。
例子:
import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()
# Terminate the process
proc.terminate() # sends a SIGTERM
没有官方 API 可以做到这一点,不。
您需要使用平台 API 来终止线程,例如 pthread_kill 或 TerminateThread。 您可以访问此类 API,例如通过 pythonwin 或通过 ctypes。
请注意,这本质上是不安全的。 如果被杀死的线程在被杀死时具有 GIL,则可能会导致无法收集的垃圾(来自堆栈帧的局部变量成为垃圾),并可能导致死锁。
如果您试图终止整个程序,您可以将线程设置为“守护进程”。 见Thread.daemon
正如其他人提到的,规范是设置停止标志。 对于轻量级(没有 Thread 的子类化,没有全局变量),可以选择 lambda 回调。 (注意if stop()
的括号。)
import threading
import time
def do_work(id, stop):
print("I am thread", id)
while True:
print("I am thread {} doing something".format(id))
if stop():
print(" Exiting loop.")
break
print("Thread {}, signing off".format(id))
def main():
stop_threads = False
workers = []
for id in range(0,3):
tmp = threading.Thread(target=do_work, args=(id, lambda: stop_threads))
workers.append(tmp)
tmp.start()
time.sleep(3)
print('main: done sleeping; time to stop the threads.')
stop_threads = True
for worker in workers:
worker.join()
print('Finis.')
if __name__ == '__main__':
main()
将print()
替换为始终刷新的pr()
函数( sys.stdout.flush()
)可以提高 shell 输出的精度。
(仅在 Windows/Eclipse/Python3.3 上测试过)
在 Python 中,您根本无法直接杀死 Thread。
如果你真的不需要一个线程(!),你可以做的不是使用threading包,而是使用multiprocessing包。 在这里,要杀死一个进程,您可以简单地调用该方法:
yourProcess.terminate() # kill the process!
Python 将TerminateProcess()
您的进程(在 Unix 上通过 SIGTERM 信号,而在 Windows 上通过TerminateProcess()
调用)。 使用 Queue 或 Pipe 时要注意使用它! (它可能会破坏队列/管道中的数据)
请注意, multiprocessing.Event
和multiprocessing.Semaphore
工作方式分别与threading.Event
和threading.Semaphore
完全相同。 事实上,第一个是后者的克隆。
如果您真的需要使用线程,则无法直接杀死它。 但是,您可以做的是使用“守护线程” 。 事实上,在 Python 中,一个 Thread 可以被标记为daemon :
yourThread.daemon = True # set the Thread as a "daemon thread"
当没有存活的非守护线程时,主程序将退出。 换句话说,当您的主线程(当然是非守护线程)完成其操作时,即使仍有一些守护线程在工作,程序也会退出。
注意,在调用start()
方法之前需要将 Thread 设置为daemon
!
当然,即使使用multiprocessing
,您也可以而且应该使用daemon
。 在这里,当主进程退出时,它会尝试终止其所有守护进程。
最后,请注意sys.exit()
和os.kill()
不是选择。
这是基于thread2 -- 可杀死的线程(Python 配方)
您需要调用 PyThreadState_SetasyncExc(),它只能通过 ctypes 获得。
这仅在 Python 2.7.3 上进行过测试,但很可能适用于其他最近的 2.x 版本。
import ctypes
def terminate_thread(thread):
"""Terminates a python thread from another thread.
:param thread: a threading.Thread instance
"""
if not thread.isAlive():
return
exc = ctypes.py_object(SystemExit)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(thread.ident), exc)
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
你永远不应该在没有配合的情况下强行杀死一个线程。
杀死一个线程会删除任何 try/finally 块设置的保证,因此您可能会锁定锁定、打开文件等。
您唯一可以争辩说强制杀死线程是一个好主意的时候是快速杀死程序,而不是单线程。
如果您显式调用time.sleep()
作为线程的一部分(例如轮询某些外部服务),对 Phillipe 方法的改进是在您sleep()
任何地方使用event
的wait()
方法中的超时
例如:
import threading
class KillableThread(threading.Thread):
def __init__(self, sleep_interval=1):
super().__init__()
self._kill = threading.Event()
self._interval = sleep_interval
def run(self):
while True:
print("Do Something")
# If no kill signal is set, sleep for the interval,
# If kill signal comes in while sleeping, immediately
# wake up and handle
is_killed = self._kill.wait(self._interval)
if is_killed:
break
print("Killing Thread")
def kill(self):
self._kill.set()
然后运行它
t = KillableThread(sleep_interval=5)
t.start()
# Every 5 seconds it prints:
#: Do Something
t.kill()
#: Killing Thread
使用wait()
而不是sleep()
并定期检查事件的优点是您可以在更长的睡眠间隔内进行编程,线程几乎立即停止(否则您将使用sleep()
ing)并且在我看来,处理退出的代码要简单得多。
您可以通过将跟踪安装到将退出线程的线程中来终止线程。 有关一种可能的实现,请参阅附加链接。
绝对可以实现Thread.stop
方法,如以下示例代码所示:
import sys
import threading
import time
class StopThread(StopIteration):
pass
threading.SystemExit = SystemExit, StopThread
class Thread2(threading.Thread):
def stop(self):
self.__stop = True
def _bootstrap(self):
if threading._trace_hook is not None:
raise ValueError('Cannot run thread with tracing!')
self.__stop = False
sys.settrace(self.__trace)
super()._bootstrap()
def __trace(self, frame, event, arg):
if self.__stop:
raise StopThread()
return self.__trace
class Thread3(threading.Thread):
def _bootstrap(self, stop_thread=False):
def stop():
nonlocal stop_thread
stop_thread = True
self.stop = stop
def tracer(*_):
if stop_thread:
raise StopThread()
return tracer
sys.settrace(tracer)
super()._bootstrap()
###############################################################################
def main():
test1 = Thread2(target=printer)
test1.start()
time.sleep(1)
test1.stop()
test1.join()
test2 = Thread2(target=speed_test)
test2.start()
time.sleep(1)
test2.stop()
test2.join()
test3 = Thread3(target=speed_test)
test3.start()
time.sleep(1)
test3.stop()
test3.join()
def printer():
while True:
print(time.time() % 1)
time.sleep(0.1)
def speed_test(count=0):
try:
while True:
count += 1
except StopThread:
print('Count =', count)
if __name__ == '__main__':
main()
Thread3
类似乎比Thread2
类运行代码快大约 33%。
最好不要杀死线程。 一种方法可能是在线程的循环中引入“try”块并在您想要停止线程时抛出异常(例如,中断/返回/...停止您的 for/while/...)。 我已经在我的应用程序上使用了它并且它有效......
我参加这个游戏已经很晚了,但我一直在努力解决一个类似的问题,以下内容似乎完美地解决了我的问题,并让我在守护子线程退出时进行一些基本的线程状态检查和清理:
import threading
import time
import atexit
def do_work():
i = 0
@atexit.register
def goodbye():
print ("'CLEANLY' kill sub-thread with value: %s [THREAD: %s]" %
(i, threading.currentThread().ident))
while True:
print i
i += 1
time.sleep(1)
t = threading.Thread(target=do_work)
t.daemon = True
t.start()
def after_timeout():
print "KILL MAIN THREAD: %s" % threading.currentThread().ident
raise SystemExit
threading.Timer(2, after_timeout).start()
产量:
0
1
KILL MAIN THREAD: 140013208254208
'CLEANLY' kill sub-thread with value: 2 [THREAD: 140013674317568]
以下解决方法可用于终止线程:
kill_threads = False
def doSomething():
global kill_threads
while True:
if kill_threads:
thread.exit()
......
......
thread.start_new_thread(doSomething, ())
这甚至可以用于从主线程终止线程,其代码是在另一个模块中编写的。 我们可以在该模块中声明一个全局变量并使用它来终止在该模块中产生的线程。
我通常使用它来终止程序出口处的所有线程。 这可能不是终止线程的完美方式,但可能会有所帮助。
from ctypes import *
pthread = cdll.LoadLibrary("libpthread-2.15.so")
pthread.pthread_cancel(c_ulong(t.ident))
t是您的Thread
对象。
阅读 python 源代码( Modules/threadmodule.c
和Python/thread_pthread.h
)你可以看到Thread.ident
是一个pthread_t
类型,所以你可以做任何pthread
在 python 中可以做的事情,使用libpthread
。
我想补充的一件事是,如果您在线程库 Python 中阅读官方文档,建议避免使用“恶魔”线程,当您不希望线程突然结束时,带有 Paolo Rovelli提到的标志。
来自官方文档:
守护线程在关机时突然停止。 他们的资源(如打开的文件、数据库事务等)可能无法正常释放。 如果您希望您的线程正常停止,请将它们设为非守护进程并使用合适的信号机制,例如事件。
我认为创建守护线程取决于您的应用程序,但总的来说(在我看来)最好避免杀死它们或使它们成为守护线程。 在多处理中,您可以使用is_alive()
检查进程状态并“终止”以完成它们(也可以避免 GIL 问题)。 但是,当您在 Windows 中执行代码时,有时会发现更多问题。
并且永远记住,如果您有“活动线程”,Python 解释器将运行以等待它们。 (因为这个守护进程可以帮助你,如果不重要突然结束)。
有一个为此目的而构建的库, stopit 。 尽管这里列出的一些相同的注意事项仍然适用,但至少这个库提供了一种常规的、可重复的技术来实现既定目标。
这是另一种方法,但代码非常干净和简单,可在 2021 年在 Python 3.7 中运行:
import ctypes
def kill_thread(thread):
"""
thread: a threading.Thread object
"""
thread_id = thread.ident
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
改编自: https : //www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/
只是为了建立@SCB 的想法(这正是我所需要的)来创建一个具有自定义函数的 KillableThread 子类:
from threading import Thread, Event
class KillableThread(Thread):
def __init__(self, sleep_interval=1, target=None, name=None, args=(), kwargs={}):
super().__init__(None, target, name, args, kwargs)
self._kill = Event()
self._interval = sleep_interval
print(self._target)
def run(self):
while True:
# Call custom function with arguments
self._target(*self._args)
# If no kill signal is set, sleep for the interval,
# If kill signal comes in while sleeping, immediately
# wake up and handle
is_killed = self._kill.wait(self._interval)
if is_killed:
break
print("Killing Thread")
def kill(self):
self._kill.set()
if __name__ == '__main__':
def print_msg(msg):
print(msg)
t = KillableThread(10, print_msg, args=("hello world"))
t.start()
time.sleep(6)
print("About to kill thread")
t.kill()
自然地,与@SBC 一样,线程不会等待运行新循环来停止。 在此示例中,您将看到“即将终止线程”之后打印的“终止线程”消息,而不是再等待 4 秒让线程完成(因为我们已经睡了 6 秒)。
KillableThread 构造函数中的第二个参数是您的自定义函数(此处为 print_msg)。 Args 参数是在此处调用函数 (("hello world")) 时将使用的参数。
一个扩展线程模块功能的小模块——允许一个线程在另一个线程的上下文中引发异常。 通过提高
SystemExit
,您最终可以杀死 python 线程。
import threading
import ctypes
def _async_raise(tid, excobj):
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError("PyThreadState_SetAsyncExc failed")
class Thread(threading.Thread):
def raise_exc(self, excobj):
assert self.isAlive(), "thread must be started"
for tid, tobj in threading._active.items():
if tobj is self:
_async_raise(tid, excobj)
return
# the thread was alive when we entered the loop, but was not found
# in the dict, hence it must have been already terminated. should we raise
# an exception here? silently ignore?
def terminate(self):
# must raise the SystemExit type, instead of a SystemExit() instance
# due to a bug in PyThreadState_SetAsyncExc
self.raise_exc(SystemExit)
因此,它允许“线程在另一个线程的上下文中引发异常”,这样,终止的线程可以处理终止而无需定期检查中止标志。
但是,根据其原始来源,此代码存在一些问题。
- 只有在执行 python 字节码时才会引发异常。 如果您的线程调用本机/内置阻塞函数,则仅当执行返回到 python 代码时才会引发异常。
- 如果内置函数在内部调用 PyErr_Clear(),也会出现问题,这将有效地取消您的挂起异常。 您可以尝试再次提高它。
- 只有异常类型可以安全地引发。 异常实例可能会导致意外行为,因此受到限制。
- 例如:t1.raise_exc(TypeError) 而不是 t1.raise_exc(TypeError("blah"))。
- 恕我直言,这是一个错误,我将其报告为一个错误。 有关更多信息,请访问http://mail.python.org/pipermail/python-dev/2006-August/068158.html
- 我要求在内置线程模块中公开这个函数,但是由于 ctypes 已经成为一个标准库(从 2.5 开始),并且这个
功能不太可能与实现无关,它可能会被保留
未曝光。
假设您想要多个线程具有相同的功能,恕我直言,这是通过 id 停止一个的最简单的实现:
import time
from threading import Thread
def doit(id=0):
doit.stop=0
print("start id:%d"%id)
while 1:
time.sleep(1)
print(".")
if doit.stop==id:
doit.stop=0
break
print("end thread %d"%id)
t5=Thread(target=doit, args=(5,))
t6=Thread(target=doit, args=(6,))
t5.start() ; t6.start()
time.sleep(2)
doit.stop =5 #kill t5
time.sleep(2)
doit.stop =6 #kill t6
好东西就在这里,你可以有多个相同和不同的功能,并通过functionname.stop
停止它们
如果您只想拥有该函数的一个线程,则无需记住 id。 停止,如果doit.stop
> 0。
正如@Kozyarchuk 的回答中所述,安装跟踪有效。 由于此答案不包含任何代码,因此这是一个现成可用的示例:
import sys, threading, time
class TraceThread(threading.Thread):
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
def start(self):
self._run = self.run
self.run = self.settrace_and_run
threading.Thread.start(self)
def settrace_and_run(self):
sys.settrace(self.globaltrace)
self._run()
def globaltrace(self, frame, event, arg):
return self.localtrace if event == 'call' else None
def localtrace(self, frame, event, arg):
if self.killed and event == 'line':
raise SystemExit()
return self.localtrace
def f():
while True:
print('1')
time.sleep(2)
print('2')
time.sleep(2)
print('3')
time.sleep(2)
t = TraceThread(target=f)
t.start()
time.sleep(2.5)
t.killed = True
它在打印1
和2
后停止。 3
不打印。
Python版本:3.8
使用守护线程来执行我们想要的,如果我们想要终止守护线程,我们只需要让父线程退出,然后系统就会终止父线程创建的守护线程。
还支持协程和协程功能。
def main():
start_time = time.perf_counter()
t1 = ExitThread(time.sleep, (10,), debug=False)
t1.start()
time.sleep(0.5)
t1.exit()
try:
print(t1.result_future.result())
except concurrent.futures.CancelledError:
pass
end_time = time.perf_counter()
print(f"time cost {end_time - start_time:0.2f}")
下面是 ExitThread 源代码
import concurrent.futures
import threading
import typing
import asyncio
class _WorkItem(object):
""" concurrent\futures\thread.py
"""
def __init__(self, future, fn, args, kwargs, *, debug=None):
self._debug = debug
self.future = future
self.fn = fn
self.args = args
self.kwargs = kwargs
def run(self):
if self._debug:
print("ExitThread._WorkItem run")
if not self.future.set_running_or_notify_cancel():
return
try:
coroutine = None
if asyncio.iscoroutinefunction(self.fn):
coroutine = self.fn(*self.args, **self.kwargs)
elif asyncio.iscoroutine(self.fn):
coroutine = self.fn
if coroutine is None:
result = self.fn(*self.args, **self.kwargs)
else:
result = asyncio.run(coroutine)
if self._debug:
print("_WorkItem done")
except BaseException as exc:
self.future.set_exception(exc)
# Break a reference cycle with the exception 'exc'
self = None
else:
self.future.set_result(result)
class ExitThread:
""" Like a stoppable thread
Using coroutine for target then exit before running may cause RuntimeWarning.
"""
def __init__(self, target: typing.Union[typing.Coroutine, typing.Callable] = None
, args=(), kwargs={}, *, daemon=None, debug=None):
#
self._debug = debug
self._parent_thread = threading.Thread(target=self._parent_thread_run, name="ExitThread_parent_thread"
, daemon=daemon)
self._child_daemon_thread = None
self.result_future = concurrent.futures.Future()
self._workItem = _WorkItem(self.result_future, target, args, kwargs, debug=debug)
self._parent_thread_exit_lock = threading.Lock()
self._parent_thread_exit_lock.acquire()
self._parent_thread_exit_lock_released = False # When done it will be True
self._started = False
self._exited = False
self.result_future.add_done_callback(self._release_parent_thread_exit_lock)
def _parent_thread_run(self):
self._child_daemon_thread = threading.Thread(target=self._child_daemon_thread_run
, name="ExitThread_child_daemon_thread"
, daemon=True)
self._child_daemon_thread.start()
# Block manager thread
self._parent_thread_exit_lock.acquire()
self._parent_thread_exit_lock.release()
if self._debug:
print("ExitThread._parent_thread_run exit")
def _release_parent_thread_exit_lock(self, _future):
if self._debug:
print(f"ExitThread._release_parent_thread_exit_lock {self._parent_thread_exit_lock_released} {_future}")
if not self._parent_thread_exit_lock_released:
self._parent_thread_exit_lock_released = True
self._parent_thread_exit_lock.release()
def _child_daemon_thread_run(self):
self._workItem.run()
def start(self):
if self._debug:
print(f"ExitThread.start {self._started}")
if not self._started:
self._started = True
self._parent_thread.start()
def exit(self):
if self._debug:
print(f"ExitThread.exit exited: {self._exited} lock_released: {self._parent_thread_exit_lock_released}")
if self._parent_thread_exit_lock_released:
return
if not self._exited:
self._exited = True
if not self.result_future.cancel():
if self.result_future.running():
self.result_future.set_exception(concurrent.futures.CancelledError())
这似乎适用于 Windows 7 上的 pywin32
my_thread = threading.Thread()
my_thread.start()
my_thread._Thread__stop()
Pieter Hintjens —— ØMQ 项目的创始人之一 —— 说,使用 ØMQ 并避免同步原语(如锁、互斥、事件等)是编写多线程程序的最明智和最安全的方式:
http://zguide.zeromq.org/py:all#Multithreading-with-ZeroMQ
这包括告诉子线程它应该取消它的工作。 这可以通过为线程配备 ØMQ 套接字并在该套接字上轮询一条消息说它应该取消来完成。
该链接还提供了使用 ØMQ 的多线程 python 代码示例。
另一种方法是使用signal.pthread_kill
发送停止信号。
from signal import pthread_kill, SIGTSTP
from threading import Thread
from itertools import count
from time import sleep
def target():
for num in count():
print(num)
sleep(1)
thread = Thread(target=target)
thread.start()
sleep(5)
pthread_kill(thread.ident, SIGTSTP)
结果
0
1
2
3
4
[14]+ Stopped
只需使用
if thread.is_alive():
print("thread alive")
else:
print("thread is killed")
它会自动杀死线程
如果您确实需要终止子任务的能力,请使用替代实现。 multiprocessing
和gevent
都支持不分青红皂白地杀死“线程”。
Python 的线程不支持取消。 想都别想。 您的代码很可能会死锁、损坏或泄漏内存,或者具有其他意外的“有趣的”难以调试的效果,这些效果很少发生且不确定。
您可以在进程中执行您的命令,然后使用进程 ID 终止它。 我需要在两个线程之间进行同步,其中一个线程本身不会返回。
processIds = []
def executeRecord(command):
print(command)
process = subprocess.Popen(command, stdout=subprocess.PIPE)
processIds.append(process.pid)
print(processIds[0])
#Command that doesn't return by itself
process.stdout.read().decode("utf-8")
return;
def recordThread(command, timeOut):
thread = Thread(target=executeRecord, args=(command,))
thread.start()
thread.join(timeOut)
os.kill(processIds.pop(), signal.SIGINT)
return;
使用 setDaemon(True) 启动子线程。
def bootstrap(_filename):
mb = ModelBootstrap(filename=_filename) # Has many Daemon threads. All get stopped automatically when main thread is stopped.
t = threading.Thread(target=bootstrap,args=('models.conf',))
t.setDaemon(False)
while True:
t.start()
time.sleep(10) # I am just allowing the sub-thread to run for 10 sec. You can listen on an event to stop execution.
print('Thread stopped')
break
最简单的方法是这样的:
from threading import Thread
from time import sleep
def do_something():
global thread_work
while thread_work:
print('doing something')
sleep(5)
print('Thread stopped')
thread_work = True
Thread(target=do_something).start()
sleep(5)
thread_work = False
这是一个不好的答案,请参阅评论
这是如何做到的:
from threading import *
...
for thread in enumerate():
if thread.isAlive():
try:
thread._Thread__stop()
except:
print(str(thread.getName()) + ' could not be terminated'))
给它几秒钟,然后您的线程应该停止。 还要检查thread._Thread__delete()
方法。
为方便起见,我建议使用thread.quit()
方法。 例如,如果您的线程中有一个套接字,我建议在您的套接字句柄类中创建一个quit()
方法,终止该套接字,然后在您的quit()
内运行一个thread._Thread__stop()
quit()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.