Python 线程启动和关闭

线程启动和关闭的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值