python杀死一个线程的方法


Posted in Python onSeptember 06, 2015

最近在项目中遇到这一需求:

我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,4秒钟如果你还没有读取完成或者连接成功,我就不等了,很可能对方已经宕机或者拒绝了。这样可以批量做一些事情而不需要一直等,浪费时间。

结合我的需求,我想到这种办法:

1、在主进程执行,调用一个进程执行函数,然后主进程sleep,等时间到了,就kill 执行函数的进程。

测试一个例子:

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函数,这个函数式用来等待一个线程结束的,如果这个函数没有结束的话,那么,就会阻塞当前运行的程序。关键是,这个参数有一个可选参数:join([timeout]):  阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。

不多说了贴下面代码大家看下:

#!/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:   
      #//添加你要做的事情,如果成功了就设置一下<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()时,好像工作不正常,没有找出真正的原因是什么。已经是很强大了。哈哈。

Python 相关文章推荐
python中range()与xrange()用法分析
Sep 21 Python
python中urlparse模块介绍与使用示例
Nov 19 Python
Python3实现腾讯云OCR识别
Nov 27 Python
Python3列表内置方法大全及示例代码小结
May 10 Python
Python DataFrame一列拆成多列以及一行拆成多行
Aug 06 Python
使用matplotlib绘制图例标签中带有公式的图
Dec 13 Python
Python 元组拆包示例(Tuple Unpacking)
Dec 24 Python
Python爬虫破解登陆哔哩哔哩的方法
Nov 17 Python
Python制作简单的剪刀石头布游戏
Dec 10 Python
python中uuid模块实例浅析
Dec 29 Python
python常见的占位符总结及用法
Jul 02 Python
python保存图片的四个常用方法
Feb 28 Python
在Python的Flask框架中验证注册用户的Email的方法
Sep 02 #Python
Python实现身份证号码解析
Sep 01 #Python
实例Python处理XML文件的方法
Aug 31 #Python
通过实例浅析Python对比C语言的编程思想差异
Aug 30 #Python
使用Python脚本将文字转换为图片的实例分享
Aug 29 #Python
Python中常见的数据类型小结
Aug 29 #Python
深入解析Python中的lambda表达式的用法
Aug 28 #Python
You might like
php获取某个目录大小的代码
2008/09/10 PHP
PHP结合jQuery插件ajaxFileUpload实现异步上传文件实例
2020/08/17 PHP
PHP动态生成指定大小随机图片的方法
2016/03/25 PHP
php反射学习之不用new方法实例化类操作示例
2019/06/14 PHP
jQuery 操作option的实现代码
2011/03/03 Javascript
第七篇Bootstrap表单布局实例代码详解(三种表单布局)
2016/06/21 Javascript
AngularJS基础 ng-mousemove 指令简单示例
2016/08/02 Javascript
AngularJS入门教程之迭代器过滤详解
2016/08/18 Javascript
Angular ng-repeat 对象和数组遍历实例
2016/09/14 Javascript
Angular.js中用ng-repeat-start实现自定义显示
2016/10/18 Javascript
微信小程序 Toast自定义实例详解
2017/01/20 Javascript
React Native时间转换格式工具类分享
2017/10/24 Javascript
详解React 在服务端渲染的实现
2017/11/16 Javascript
d3.js实现自定义多y轴折线图的示例代码
2018/05/30 Javascript
ES6与CommonJS中的模块处理的区别
2018/06/13 Javascript
详解微信小程序缓存--缓存时效性
2019/05/02 Javascript
element-ui 本地化使用教程详解
2019/10/28 Javascript
使用typescript改造koa开发框架的实现
2020/02/04 Javascript
微信小程序scroll-view的滚动条设置实现
2020/03/02 Javascript
Element-ui el-tree新增和删除节点后如何刷新tree的实例
2020/08/31 Javascript
[02:44]DOTA2英雄基础教程 钢背兽
2013/12/19 DOTA
[02:37]TI8勇士令状不朽珍藏II视频展示
2018/06/23 DOTA
Numpy array数据的增、删、改、查实例
2018/06/04 Python
详解python中的装饰器
2018/07/10 Python
python实现飞机大战
2018/09/11 Python
softmax及python实现过程解析
2019/09/30 Python
Django中FilePathField字段的用法
2020/05/21 Python
意大利高端时尚买手店:Stefania Mode
2018/03/01 全球购物
自我评价正确写法范文
2013/12/10 职场文书
敬老院标语
2014/06/27 职场文书
社区环境卫生倡议书
2015/04/29 职场文书
2015年中秋晚会主持稿
2015/07/30 职场文书
2016年端午节寄语
2015/12/04 职场文书
求职自我评价参考范文
2019/05/16 职场文书
MySQL 常见的数据表设计误区汇总
2021/06/07 MySQL
Python+Tkinter制作专属图形化界面
2022/04/01 Python