最近开发的项目中需要实现线程的暂停与恢复,但 Python 的 threading 模块并没有提供相关功能,看了一遍网上给出的例子,几乎都是用标志位显现,类似于:
while flag:
time.sleep(1)
...
此方式并不能实现随时暂停随时恢复,只能是程序运行到这个代码块时才有效,同时在 while 循环里面延时,不是很简洁高效。于是从谷歌上找到了完美的解决方案,不需要标志位就能实现,代码如下:
import ctypes
from threading import Thread as _Thread
class Thread(_Thread):
def __init__(self, target = None, args = (), kwargs = None, name = ""):
_Thread.__init__(self, target = target, args = args, kwargs = kwargs, name = name)
self.kernel32 = ctypes.windll.kernel32
def stop(self):
ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, ctypes.py_object(SystemExit))
def start(self):
_Thread.start(self)
def pause(self):
handle = self.kernel32.OpenThread(0x0002, False, self.ident)
self.kernel32.SuspendThread(handle)
self.kernel32.CloseHandle(handle)
def resume(self):
handle = self.kernel32.OpenThread(0x0002, False, self.ident)
self.kernel32.ResumeThread(handle)
self.kernel32.CloseHandle(handle)