欧美三区_成人在线免费观看视频_欧美极品少妇xxxxⅹ免费视频_a级毛片免费播放_鲁一鲁中文字幕久久_亚洲一级特黄

python殺死一個線程的方法

系統(tǒng) 1682 0

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

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

結合我的需求,我想到這種辦法:

1、在主進程執(zhí)行,調用一個進程執(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()
          

經過測試只定了4秒鐘。

經過我的一番折騰,想到了join函數(shù),這個函數(shù)式用來等待一個線程結束的,如果這個函數(shù)沒有結束的話,那么,就會阻塞當前運行的程序。關鍵是,這個參數(shù)有一個可選參數(shù):join([timeout]):? 阻塞當前上下文環(huán)境的線程,直到調用此方法的線程終止或到達指定的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:   
      #//添加你要做的事情,如果成功了就設置一下
            
              self.thread_stop變量。
            
             
[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()時,好像工作不正常,沒有找出真正的原因是什么。已經是很強大了。哈哈。


更多文章、技術交流、商務合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 我不卡午夜 | 欧美亚洲视频在线观看 | 精品一区二区久久久久久久网站 | av电影直播| 欧美一区二区三区在线看 | 欧美黑人疯狂性受xxxxx喷水 | 日日夜夜爱 | 国产亚洲精品久久久久久小说 | 国产精品亚洲综合第一区 | 亚洲精品国产网红在线 | 91热久久免费频精品黑人99 | 日韩中文字 | 欧美日韩亚洲精品国产色 | 欧美视频在线播放 | 激情视频区 | 欧美狠狠操 | 成人国产网站 | 久久精品91久久久久久再现 | 亚洲www.| 中文字幕不卡在线观看 | 国产色婷婷亚洲99精品小说 | 亚洲一区二区三区日本久久九 | 能看的毛片网站 | www.国产精| 国产在线不卡一区 | 色视频网站在线观看 | 色一欲一性一乱一区二区三区 | 99只有精品 | 经典香港一级a毛片免费看 亚洲精品国产精品国自产观看 | 久久久久久久国产精品毛片 | 96久久久久久| 欧美成人久久一级c片免费 91在线免费视频 | 91久久亚洲精品一区二区 | 亚洲精品久久久一区二区三区 | 成人在线小视频 | 毛片少妇爽到高潮特黄A片 六月色播 | jiuse在线| 91亚洲精品一区二区福利 | 91精品啪国产在线观看免费牛牛 | 国产成人精品综合 | 欧美成人伊人十综合色 |