在python中杀死一个线程 - 简单的程序似乎不起作用

时间:2016-07-29 21:29:23

标签: python multithreading

以下简单的python程序似乎不起作用。它是http://code.activestate.com/recipes/496960-thread2-killable-threads/

中提到的配方的简化

它产生了一个带有无限for循环的单独线程,并试图杀死它。

PyThreadState_SetAsyncExc返回0,它应该是"无效的threadId",因此生成的线程不会被杀死。我错过了什么?

import threading
from threading import Thread
import time

def runThread():
    def f():
        while(1):
            pass
    thr = Thread(target=f, args=[])
    thr.start()
    for tid, tobj in threading._active.items():
        if tobj == thr:
            return (tid, tobj)
    return (-1, None)

import ctypes

def main():
    (tid, thr) = runThread()
    time.sleep(5)
    print "ThreadId is ", thr.ident
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thr.ident,   ctypes.py_object(Exception("Hello world")))
    print res
    time.sleep(2)
    print "Threads are ", str(threading._active)

if __name__ == "__main__":
    main()

0 个答案:

没有答案