最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python殺死一個線程的方法

 更新時間:2015年09月06日 09:39:30   投稿:mrr  
由于python線程沒有提供abort方法,所以我們需要自己想辦法解決此問題,面對這一問題,小編幫大家解決phthon殺死一個線程的方法,需要的朋友一起來學習吧

最近在項目中遇到這一需求:

我需要一個函數(shù)工作,比如遠程連接一個端口,遠程讀取文件等,但是我給的時間有限,比如,4秒鐘如果你還沒有讀取完成或者連接成功,我就不等了,很可能對方已經(jīng)宕機或者拒絕了。這樣可以批量做一些事情而不需要一直等,浪費時間。

結(jié)合我的需求,我想到這種辦法:

1、在主進程執(zhí)行,調(diào)用一個進程執(zhí)行函數(shù),然后主進程sleep,等時間到了,就kill 執(zhí)行函數(shù)的進程。

測試一個例子:

import time 
import threading 
def p(i): 
  print i 
class task(threading.Thread): 
  def __init__(self,fun,i): 
    threading.Thread.__init__(self) 
    self.fun = fun 
    self.i = i 
    self.thread_stop = False 
  def run(self): 
    while not self.thread_stop: 
      self.fun(self.i) 
  def stop(self): 
    self.thread_stop = True 
def test(): 
  thread1 = task(p,2) 
  thread1.start() 
  time.sleep(4) 
  thread1.stop() 
  return 
if __name__ == '__main__': 
  test()

經(jīng)過測試只定了4秒鐘。

經(jīng)過我的一番折騰,想到了join函數(shù),這個函數(shù)式用來等待一個線程結(jié)束的,如果這個函數(shù)沒有結(jié)束的話,那么,就會阻塞當前運行的程序。關(guān)鍵是,這個參數(shù)有一個可選參數(shù):join([timeout]):  阻塞當前上下文環(huán)境的線程,直到調(diào)用此方法的線程終止或到達指定的timeout(可選參數(shù))。

不多說了貼下面代碼大家看下:

#!/usr/bin/env python 
#-*-coding:utf-8-*- 
''''' 
author:cogbee 
time:2014-6-13 
function:readme 
''' 
import pdb 
import time 
import threading 
import os 
#pdb.set_trace() 
class task(threading.Thread): 
  def __init__(self,ip): 
    threading.Thread.__init__(self) 
    self.ip = ip 
    self.thread_stop = False 
  def run(self): 
    while not self.thread_stop:   
      #//添加你要做的事情,如果成功了就設(shè)置一下<span style="font-family: Arial, Helvetica, sans-serif;">self.thread_stop變量。</span> 
[python] view plaincopy在CODE上查看代碼片派生到我的代碼片
      if file != '': 
        self.thread_stop = True 
  def stop(self): 
    self.thread_stop = True 
def test(eachline): 
  global file 
  list = [] 
  for ip in eachline: 
    thread1 = task(ip) 
    thread1.start() 
    thread1.join(3) 
    if thread1.isAlive():   
      thread1.stop() 
      continue 
    #將可以讀取的都存起來 
    if file != '': 
      list.append(ip) 
  print list 
if __name__ == '__main__': 
  eachline = ['1.1.1.1','222.73.5.54'] 
  test(eachline)

下面給大家分享我寫的一段殺死線程的代碼。

由于python線程沒有提供abort方法,分享下面一段代碼殺死線程:

import threading 
import inspect 
import ctypes 
def _async_raise(tid, exctype):
  """raises the exception, performs cleanup if needed"""
  if not inspect.isclass(exctype):
    raise TypeError("Only types can be raised (not instances)")
  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, 0)
    raise SystemError("PyThreadState_SetAsyncExc failed")
class Thread(threading.Thread):
  def _get_my_tid(self):
    """determines this (self's) thread id"""
    if not self.isAlive():
      raise threading.ThreadError("the thread is not active")
    # do we have it cached?
    if hasattr(self, "_thread_id"):
      return self._thread_id
    # no, look for it in the _active dict
    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):
    """raises the given exception type in the context of this thread"""
    _async_raise(self._get_my_tid(), exctype)
def terminate(self):
    """raises SystemExit in the context of the given thread, which should 
    cause the thread to exit silently (unless caught)"""
    self.raise_exc(SystemExit)

使用例子:

>>> import time 
>>> from thread2 import Thread 
>>> 
>>> def f(): 
...   try: 
...     while True: 
...       time.sleep(0.1) 
...   finally: 
...     print "outta here" 
... 
>>> t = Thread(target = f) 
>>> t.start() 
>>> t.isAlive() 
True 
>>> t.terminate() 
>>> t.join() 
outta here 
>>> t.isAlive() 
False

試了一下,很不錯,只是在要kill的線程中如果有time.sleep()時,好像工作不正常,沒有找出真正的原因是什么。已經(jīng)是很強大了。哈哈。

相關(guān)文章

  • python中的異步爬蟲詳解

    python中的異步爬蟲詳解

    這篇文章主要介紹了python中的異步爬蟲詳解,所謂的異步異步?IO,就是發(fā)起一個?IO?阻塞的操作,但是不用等到它結(jié)束,可以在它執(zhí)行?IO?的過程中繼續(xù)做別的事情,當?IO?執(zhí)行完畢之后會收到它的通知,需要的朋友可以參考下
    2023-08-08
  • Python 操作mysql數(shù)據(jù)庫查詢之fetchone(), fetchmany(), fetchall()用法示例

    Python 操作mysql數(shù)據(jù)庫查詢之fetchone(), fetchmany(), fetchall()用法示例

    這篇文章主要介紹了Python 操作mysql數(shù)據(jù)庫查詢之fetchone(), fetchmany(), fetchall()用法,結(jié)合實例形式分析了Python使用pymysql模塊的fetchone(), fetchmany(), fetchall()方法進行mysql數(shù)據(jù)庫查詢的操作技巧,需要的朋友可以參考下
    2019-10-10
  • Python進階多線程爬取網(wǎng)頁項目實戰(zhàn)

    Python進階多線程爬取網(wǎng)頁項目實戰(zhàn)

    這篇文章主要為大家介紹了Python進階,Python多線程爬取網(wǎng)頁項目實戰(zhàn)的示例呈現(xiàn)步驟,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-10-10
  • matplotlib bar()實現(xiàn)百分比堆積柱狀圖

    matplotlib bar()實現(xiàn)百分比堆積柱狀圖

    這篇文章主要介紹了matplotlib bar()實現(xiàn)百分比堆積柱狀圖,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-02-02
  • Python中多個數(shù)組行合并及列合并的方法總結(jié)

    Python中多個數(shù)組行合并及列合并的方法總結(jié)

    下面小編就為大家分享一篇Python中多個數(shù)組行合并及列合并的方法總結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • python?argparse模塊傳參用法實例

    python?argparse模塊傳參用法實例

    這篇文章主要為大家介紹了python?argparse模塊傳參用法實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • python數(shù)組中的?k-diff?數(shù)對例題解析

    python數(shù)組中的?k-diff?數(shù)對例題解析

    這篇文章主要介紹了python數(shù)組中的?k-diff?數(shù)對例題解析,文章根據(jù)題目內(nèi)容對其進行分析以此展開主題內(nèi)容,感興趣的小伙伴可以參考一下下面文章詳情
    2022-06-06
  • Python的動態(tài)重新封裝的教程

    Python的動態(tài)重新封裝的教程

    這篇文章主要介紹了Python的動態(tài)重新封裝的教程,本文來自于IBM的官方開發(fā)者文檔,需要的朋友可以參考下
    2015-04-04
  • 詳解Python3 對象組合zip()和回退方式*zip

    詳解Python3 對象組合zip()和回退方式*zip

    這篇文章主要介紹了Python3 對象組合zip()和回退方式*zip詳解,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-05-05
  • python基于Tkinter實現(xiàn)人員管理系統(tǒng)

    python基于Tkinter實現(xiàn)人員管理系統(tǒng)

    這篇文章主要為大家詳細介紹了python基于Tkinter實現(xiàn)人員管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11

最新評論

沾化县| 博罗县| 深水埗区| 南康市| 宁化县| 临漳县| 土默特右旗| 富宁县| 婺源县| 洱源县| 三江| 重庆市| 桐乡市| 全州县| 龙陵县| 花莲县| 孝昌县| 温宿县| 霞浦县| 自治县| 阿图什市| 锡林浩特市| 正阳县| 栾城县| 昌图县| 东海县| 呼和浩特市| 海安县| 且末县| 宾阳县| 莲花县| 花莲市| 兴国县| 延安市| 随州市| 新营市| 通江县| 定兴县| 宣汉县| 金坛市| 淅川县|