Python 线程启动和关闭

Python 线程启动和关闭

  • 线程启动和关闭的Demo
    • 测试结果显示,发现至少3s才能停止线程

线程启动和关闭的Demo

  • Python自带的线程函数,发现没有停止的功能,有些需要重载后使用,但是这里还是用了网上的一个脚本通用的方法,实测还是有效的,只是从stop thread开始到真正退出,时间有延迟;实测多次发现至少需要3s
import threading
import sys, os, time
import inspect
import ctypes
import thread


def TestThreadExit():
    print "Start Now"
    Thrd = threading.Thread(target=ThrdMointor)
    Thrd.start()

    print "Start Thrd now "
    time_counter = 10
    while time_counter > 0:
        print "timer = " + str(time_counter) + "\n"
        time_counter = time_counter - 1
        if time_counter <= 0:
            if Thrd.isAlive():
                stop_thread(Thrd)

            print "time end..."
        time.sleep(1)

    while Thrd.isAlive():
        if Thrd.isAlive():
            stop_thread(Thrd)
            print "The Thrd is still alive "
        else:
            print "The Thrd is dead."

        time.sleep(0.2)
    Thrd.join()


def ThrdMointor():
    timeCounter = 0
    while True:
        print "Test Monitor time counter = " + str(timeCounter) + '\n'
        time.sleep(1)
        timeCounter += 1


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)



if __name__=="__main__":
    TestThreadExit()


测试结果显示,发现至少3s才能停止线程


Start Now
Test Monitor time counter = 0

Start Thrd now 
timer = 10

Test Monitor time counter = 1

timer = 9

Test Monitor time counter = 2

timer = 8

Test Monitor time counter = 3

timer = 7

Test Monitor time counter = 4

timer = 6

Test Monitor time counter = 5

timer = 5

Test Monitor time counter = 6

timer = 4

Test Monitor time counter = 7

timer = 3

Test Monitor time counter = 8

timer = 2

Test Monitor time counter = 9

timer = 1

time end...
Test Monitor time counter = 10

The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
Test Monitor time counter = 11

The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
Test Monitor time counter = 12

The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
The Thrd is still alive 
Test Monitor time counter = 13

Process finished with exit code 0

你可能感兴趣的:(Python,python)