python 強制停止執行緒

2022-08-21 16:42:15 字數 2235 閱讀 7361

2020-12-13更新:

ctypes終止執行緒:

# coding=utf-8

import threading

import time

import ctypes

import inspect

import asyncio

def _async_raise(tid, exctype):

"""raises the exception, performs cleanup if needed"""

try:

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:

# pass

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")

except exception as err:

print(err)

def stop_thread(thread):

"""終止執行緒"""

_async_raise(thread.ident, systemexit)

class countdowntask:

def run(self, n):

while true:

# 將要執行的任務放在此處

# 示例

print("t-minus {}\n".format(n))

n -= 1

asyncio.sleep(100)

# time.sleep(100)

# end

# 示例

# stop threading

countdowntask = countdowntask()

th = threading.thread(target=countdowntask.run, args=(10,)) # args可以給run傳參

th.start()

time.sleep(2)

stop_thread(th) # signal termination

# end

------------------------------------分割線---------------------------------------

原文:

# coding=utf-8

import threading

import time

class countdowntask:

def __init__(self):

self._running = true

def terminate(self):

self._running = false

def run(self, n):

while self._running:

# 將要執行的任務放在此處

# 示例

print("t-minus {}\n".format(n))

n -= 1

time.sleep(100)

# end

# 示例

# stop threading

countdowntask = countdowntask()

th = threading.thread(target=countdowntask.run, args=(10,)) # args可以給run傳參

th.start()

countdowntask.terminate() # signal termination

# end

Python 強制停止子執行緒

timer 一般會設定乙個間隔時間,然後才開乙個子執行緒執行需要執行的函式。cancel 函式只能取消還未開始執行的 timer,也就是取消該 timer。如果 timer 已經開啟子執行緒執行函式了,用 cancel 函式 是不能停止子執行緒執行的,子執行緒會一直執行,直到結束。cancel st...

oracle 強制停止job

一 溫柔的方法 1 檢視所有job select from dba jobs 2 檢視正在執行的job select from dba jobs running 3 根據sid查出對應的session select sid,serial from v session where sid sid 4 ...

python3 執行緒的停止

1 threading類 設定子執行緒為守護執行緒,setdaemon true 當主線程結束時,守護執行緒會自動結束 import threading def run x while x print x t threading.thread target run,args 4,daemon tru...