楼主: z74646
2843 1

[其他] Python强制关闭线程的方法是什么 [推广有奖]

  • 0关注
  • 1粉丝

本科生

75%

还不是VIP/贵宾

-

威望
0
论坛币
300 个
通用积分
0
学术水平
0 点
热心指数
1 点
信用等级
0 点
经验
890 点
帖子
55
精华
0
在线时间
12 小时
注册时间
2014-2-26
最后登录
2016-7-2

楼主
z74646 发表于 2016-3-28 23:01:04 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

在Python开发(http://www.maiziedu.com/course/python-px/中,由于经常被PythonDaemon线程阻塞,导致程序无法结束。所以向找个方法能强制关闭线程就好了,可是在网上找了很多方法都不能解决问题,可能是在MAC上面试验的,可是皇天不负有心人,终于找到了最终解决方法,详细情况见代码:

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)

class TestThread(threading.Thread):

    def run(self):

        print "begin"

        while True:

            time.sleep(0.1)

        print "end"

if __name__ == "__main__":

    t = TestThread()

    t.start()

    time.sleep(1)

    stop_thread(t)

    print "stoped"

改造后的方案,只是在 _async_raise 函数最前面,将tid转换成了c_long类型。因为传到API中的类型需要是C的长整形,不然会越界。因为在我的环境中,PID是一个较大的值。

解决方案利用的是python内置API,通过ctypes模块调用,在线程中丢出异常,使线程退出。

希望我的分享能给各位python程序猿一些帮助。


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:python exception threads reading Greater 有心人 程序 开发 网上

沙发
zxun 发表于 2016-3-31 22:14:29
好像3.4的版本里面就有一个方法是杀线程的,但是这个方法没有被写说明,也就是程序员开发了之后,官方没有支持他。看源代码吧。

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-2-7 05:48