首頁 > 後端開發 > Python教學 > Python 中的執行緒可以突然終止嗎?

Python 中的執行緒可以突然終止嗎?

DDD
發布: 2024-12-25 19:12:17
原創
854 人瀏覽過

Can Threads in Python Be Abruptly Terminated, and If So, What Are the Limitations?

有什麼方法可以突然終止執行緒嗎?

在 Python 中通常不建議在不依賴標誌或信號量的情況下終止正在運行的執行緒由於潛在的後果。但是,在某些情況下,如下所述,可能需要強制終止執行緒。

不受控制的執行緒終止

強制執行緒突然停止可能會導致問題,例如:

  • 持有需要適當的關鍵資源cleanup
  • 創建多個也需要終止的執行緒

理想情況下,執行緒應該設計為在收到退出請求訊號時優雅退出。這可以使用線程定期檢查以確定是否應該終止的共享標誌來實現。

Beispiel:

1

2

3

4

5

6

7

8

9

10

11

12

import threading

 

class StoppableThread(threading.Thread):

    def __init__(self,  *args, **kwargs):

        super().__init__(*args, **kwargs)

        self._stop_event = threading.Event()

 

    def stop(self):

        self._stop_event.set()

 

    def stopped(self):

        return self._stop_event.is_set()

登入後複製

強制執行緒終止

在某些場景下,例如處理外部庫時,例如處理外部庫時,可能需要強制終止一個執行緒。這可以使用以下程式碼來實現,該程式碼允許在特定執行緒中引發異常:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

def _async_raise(tid, exctype):

    if not inspect.isclass(exctype):

        raise TypeError("Only types can be raised (not instances)")

    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),

                                                     ctypes.py_object(exctype))

    if res == 0:

        raise ValueError("invalid thread id")

    elif res != 1:

        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)

        raise SystemError("PyThreadState_SetAsyncExc failed")

 

class ThreadWithExc(threading.Thread):

    def _get_my_tid(self):

        if not self.is_alive():

            raise threading.ThreadError("the thread is not active")

 

        if hasattr(self, "_thread_id"):

            return self._thread_id

 

        for tid, tobj in threading._active.items():

            if tobj is self:

                self._thread_id = tid

                return tid

 

        raise AssertionError("could not determine the thread's id")

 

    def raise_exc(self, exctype):

        _async_raise( self._get_my_tid(), exctype )

登入後複製

強制執行緒終止的限制

此方法有局限性如果執行緒在Python 解釋器之外執行程式碼,則可能無法運作。為了可靠的清理,建議讓執行緒捕獲特定的異常並執行適當的操作。

以上是Python 中的執行緒可以突然終止嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板