强行停止python子线程最佳方案

转自:https://blog.csdn.net/zhao_5352269/article/details/81662099

子线程的强制性终止是我们实际应用时经常需要用到的,然而python官方并没有给出相关的函数来处理这种情况。网上找到一个挺合理的解决方案,这里分享给大家。

import threading
import time
import inspect
import ctypes
 
 
def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(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(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
 
 
def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)
 
 
def test():
    while True:
        print('-------')
        time.sleep(0.5)
 
 
if __name__ == "__main__":
    t = threading.Thread(target=test)
    t.start()
    time.sleep(5.2)
    print("main thread sleep finish")
    stop_thread(t)

参考:https://blog.csdn.net/u010159842/article/details/55506011

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Python 中,线程调用主线程的方法可以使用 Queue 模块来实现。具体步骤如下: 1. 在主线程中创建一个 Queue 对象,并将需要调用的方法和参数封装成一个元组,放入队列中。 2. 在线程中,通过 Queue.get() 方法获取队列中的元组,其中包含需要调用的方法和参数。 3. 线程通过调用该方法,并将参数传递给方法。 4. 如果需要在主线程中获得该方法的返回值,可以将返回值封装成一个元组,放入另一个队列中。 5. 在主线程中,通过 Queue.get() 方法获取线程中的返回值元组,其中包含方法的返回值。 下面是一个简单的示例代码: ```python import threading import queue def main_thread_method(arg): print(f"Main thread method called with arg {arg}") def worker_thread(queue): while True: # 阻塞等待主线程传来的任务 task = queue.get() method, args = task # 调用方法,并将返回值封装成元组返回给主线程 ret = method(*args) queue.put(ret) if __name__ == "__main__": # 启动线程 q = queue.Queue() t = threading.Thread(target=worker_thread, args=(q,)) t.start() # 在主线程中将任务加入队列 q.put((main_thread_method, ("hello",))) # 等待线程返回结果 ret = q.get() print(f"Received result from worker thread: {ret}") ``` 在此示例中,主线程调用 main_thread_method 方法,并将参数 "hello" 封装成一个任务元组加入队列中。线程从队列中获取任务,并执行该方法,将返回值封装成元组后再次放入队列中。主线程从队列中获取返回值元组,其中包含方法的返回值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值