python杀死一个线程的方法杀死一个线程的方法
由于python线程没有提供abort方法,所以我们需要自己想办法解决此问题,面对这一问题,小编帮大家解决
phthon杀死一个线程的方法,需要的朋友一起来学习吧
最近在项目中遇到这一需求:
我需要一个函数工作,比如远程连接一个端口,远程读取文件等,但是我给的时间有限,比如,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:
评论0