溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python線程之定位與銷毀的實現(xiàn)

發(fā)布時間:2021-06-03 16:25:24 來源:億速云 閱讀:194 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了Python線程之定位與銷毀的實現(xiàn),內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

找出線程ID

和平時的故障排查相似,先通過 ps 命令看看目標進程的線程情況,因為已經(jīng)是 setName 設(shè)置過線程名,所以正常來說應(yīng)該是看到對應(yīng)的線程的。 直接用下面代碼來模擬這個線程:

Python 版本的多線程

#coding: utf8
import threading
import os
import time

def tt():
  info = threading.currentThread()
  while True:
    print 'pid: ', os.getpid()
    print info.name, info.ident
    time.sleep(3)

t1 = threading.Thread(target=tt)
t1.setName('OOOOOPPPPP')
t1.setDaemon(True)
t1.start()

t2 = threading.Thread(target=tt)
t2.setName('EEEEEEEEE')
t2.setDaemon(True)
t2.start()


t1.join()
t2.join()

輸出:

root@10-46-33-56:~# python t.py
pid: 5613
OOOOOPPPPP 139693508122368
pid: 5613
EEEEEEEEE 139693497632512
...

可以看到在 Python 里面輸出的線程名就是我們設(shè)置的那樣,然而 Ps 的結(jié)果卻是令我懷疑人生:

root@10-46-33-56:~# ps -Tp 5613
PID SPID TTY TIME CMD
5613 5613 pts/2 00:00:00 python
5613 5614 pts/2 00:00:00 python
5613 5615 pts/2 00:00:00 python

正常來說不該是這樣呀,我有點迷了,難道我一直都是記錯了?用別的語言版本的多線程來測試下:

C 版本的多線程

#include<stdio.h>
#include<sys/syscall.h>
#include<sys/prctl.h>
#include<pthread.h>

void *test(void *name)
{  
  pid_t pid, tid;
  pid = getpid();
  tid = syscall(__NR_gettid);
  char *tname = (char *)name;
  
  // 設(shè)置線程名字
  prctl(PR_SET_NAME, tname);
  
  while(1)
  {
    printf("pid: %d, thread_id: %u, t_name: %s\n", pid, tid, tname);
    sleep(3);
  }
}

int main()
{
  pthread_t t1, t2;
  void *ret;
  pthread_create(&t1, NULL, test, (void *)"Love_test_1");
  pthread_create(&t2, NULL, test, (void *)"Love_test_2");
  pthread_join(t1, &ret);
  pthread_join(t2, &ret);
}

輸出:

root@10-46-33-56:~# gcc t.c -lpthread && ./a.out
pid: 5575, thread_id: 5577, t_name: Love_test_2
pid: 5575, thread_id: 5576, t_name: Love_test_1
pid: 5575, thread_id: 5577, t_name: Love_test_2
pid: 5575, thread_id: 5576, t_name: Love_test_1
...

用 PS 命令再次驗證:

root@10-46-33-56:~# ps -Tp 5575
PID SPID TTY TIME CMD
5575 5575 pts/2 00:00:00 a.out
5575 5576 pts/2 00:00:00 Love_test_1
5575 5577 pts/2 00:00:00 Love_test_2

這個才是正確嘛,線程名確實是可以通過 Ps 看出來的嘛!

不過為啥 Python 那個看不到呢?既然是通過 setName 設(shè)置線程名的,那就看看定義咯:

[threading.py]
class Thread(_Verbose):
  ...
  @property
  def name(self):
    """A string used for identification purposes only.

    It has no semantics. Multiple threads may be given the same name. The
    initial name is set by the constructor.

    """
    assert self.__initialized, "Thread.__init__() not called"
    return self.__name
  def setName(self, name):
    self.name = name
  ...

看到這里其實只是在 Thread 對象的屬性設(shè)置了而已,并沒有動到根本,那肯定就是看不到咯~

這樣看起來,我們已經(jīng)沒辦法通過 ps 或者 /proc/ 這類手段在外部搜索 python 線程名了,所以我們只能在 Python 內(nèi)部來解決。

于是問題就變成了,怎樣在 Python 內(nèi)部拿到所有正在運行的線程呢?

threading.enumerate 可以完美解決這個問題!Why?

Because 在下面這個函數(shù)的 doc 里面說得很清楚了,返回所有活躍的線程對象,不包括終止和未啟動的。

[threading.py]

def enumerate():
  """Return a list of all Thread objects currently alive.

  The list includes daemonic threads, dummy thread objects created by
  current_thread(), and the main thread. It excludes terminated threads and
  threads that have not yet been started.

  """
  with _active_limbo_lock:
    return _active.values() + _limbo.values()

因為拿到的是 Thread 的對象,所以我們通過這個能到該線程相關(guān)的信息!

請看完整代碼示例:

#coding: utf8

import threading
import os
import time


def get_thread():
  pid = os.getpid()
  while True:
    ts = threading.enumerate()
    print '------- Running threads On Pid: %d -------' % pid
    for t in ts:
      print t.name, t.ident
    print
    time.sleep(1)
    
def tt():
  info = threading.currentThread()
  pid = os.getpid()
  while True:
    print 'pid: {}, tid: {}, tname: {}'.format(pid, info.name, info.ident)
    time.sleep(3)
    return

t1 = threading.Thread(target=tt)
t1.setName('Thread-test1')
t1.setDaemon(True)
t1.start()

t2 = threading.Thread(target=tt)
t2.setName('Thread-test2')
t2.setDaemon(True)
t2.start()

t3 = threading.Thread(target=get_thread)
t3.setName('Checker')
t3.setDaemon(True)
t3.start()

t1.join()
t2.join()
t3.join()

輸出:

root@10-46-33-56:~# python t_show.py
pid: 6258, tid: Thread-test1, tname: 139907597162240
pid: 6258, tid: Thread-test2, tname: 139907586672384

------- Running threads On Pid: 6258 -------
MainThread 139907616806656
Thread-test1 139907597162240
Checker 139907576182528
Thread-test2 139907586672384

------- Running threads On Pid: 6258 -------
MainThread 139907616806656
Thread-test1 139907597162240
Checker 139907576182528
Thread-test2 139907586672384

------- Running threads On Pid: 6258 -------
MainThread 139907616806656
Thread-test1 139907597162240
Checker 139907576182528
Thread-test2 139907586672384

------- Running threads On Pid: 6258 -------
MainThread 139907616806656
Checker 139907576182528
...

代碼看起來有點長,但是邏輯相當簡單,Thread-test1Thread-test2 都是打印出當前的 pid、線程 id 和 線程名字,然后 3s 后退出,這個是想模擬線程正常退出。

Checker 線程則是每秒通過 threading.enumerate 輸出當前進程內(nèi)所有活躍的線程。

可以明顯看到一開始是可以看到 Thread-test1Thread-test2的信息,當它倆退出之后就只剩下 MainThreadChecker 自身而已了。

銷毀指定線程

既然能拿到名字和線程 id,那我們也就能干掉指定的線程了!

假設(shè)現(xiàn)在 Thread-test2 已經(jīng)黑化,發(fā)瘋了,我們需要制止它,那我們就可以通過這種方式解決了:

在上面的代碼基礎(chǔ)上,增加和補上下列代碼:

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:
    ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
    raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):
  _async_raise(thread.ident, SystemExit)

def get_thread():
  pid = os.getpid()
  while True:
    ts = threading.enumerate()
    print '------- Running threads On Pid: %d -------' % pid
    for t in ts:
      print t.name, t.ident, t.is_alive()
      if t.name == 'Thread-test2':
        print 'I am go dying! Please take care of yourself and drink more hot water!'
        stop_thread(t)
    print
    time.sleep(1)

輸出

root@10-46-33-56:~# python t_show.py
pid: 6362, tid: 139901682108160, tname: Thread-test1
pid: 6362, tid: 139901671618304, tname: Thread-test2
------- Running threads On Pid: 6362 -------
MainThread 139901706389248 True
Thread-test1 139901682108160 True
Checker 139901661128448 True
Thread-test2 139901671618304 True
Thread-test2: I am go dying. Please take care of yourself and drink more hot water!

------- Running threads On Pid: 6362 -------
MainThread 139901706389248 True
Thread-test1 139901682108160 True
Checker 139901661128448 True
Thread-test2 139901671618304 True
Thread-test2: I am go dying. Please take care of yourself and drink more hot water!

pid: 6362, tid: 139901682108160, tname: Thread-test1
------- Running threads On Pid: 6362 -------
MainThread 139901706389248 True
Thread-test1 139901682108160 True
Checker 139901661128448 True
// Thread-test2 已經(jīng)不在了

一頓操作下來,雖然我們這樣對待 Thread-test2,但它還是關(guān)心著我們:多喝熱水,

PS: 熱水雖好,八杯足矣,請勿貪杯哦。

書回正傳,上述的方法是極為粗暴的,為什么這么說呢?

因為它的原理是:利用 Python 內(nèi)置的 API,觸發(fā)指定線程的異常,讓其可以自動退出;

Python線程之定位與銷毀的實現(xiàn)

上述內(nèi)容就是Python線程之定位與銷毀的實現(xiàn),你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI