recently encountered this requirement in the project:
I need a function, such as remote connection to a port, remote reading files, etc., but I give a limited time, for example, 4 seconds if you have not read the completion or the connection is successful, I will not wait, it is possible that the other side has been down or refused. This allows you to do things in bulk without having to wait and waste time.
In combination with my needs, I think of this approach:
1, in the main process execution, call a Process execution function, and then the main process sleep, and so on, the kill execution function process.
Test an example:
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 ()
It was tested for only 4 seconds.
After my toss, think of the Join function, this function is used to wait for a thread to end, if the function is not finished, then it will block the current running program. The key is that this parameter has an optional parameter: join ([timeout]): Blocks the thread of the current context until the thread that called the method terminates or arrives at the specified timeout (optional parameter).
Not much to say stick to the following code everyone look under:
#!/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): And not self.thread_stop: #//Add the things you want to do, if successful, set the self.thread_stop variable. [python] view plaincopy on code to view a snippet derived from my code slice 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 (E Achline)
Let's share the code I wrote about a thread that kills threads.
Because the Python thread does not provide the Abort method, share the following piece of code to kill the thread:
Import Threading Import Inspect import ctypes def _async_raise (Tid, Exctype): "" "raises the exception, performs cleanup I F Needed "" "if not Inspect.isclass (exctype): Raise TypeError (" Only types can is 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=nul L to revert the effect "" "Ctypes.pythonapi.PyThreadState_SetAsyncExc (TID, 0) Raise Systemerror (" Pythreadstate_setasy Ncexc failed ") class Thread (threading. Thread): Def _get_my_tid (self): "" "Determines the thread id" "" If Not Self.isalive (): Raise Threadin G.threaderror ("The thread is not active") # does 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 t Hreading._active.items (): If tobj is self:self._thread_id = Tid return tid raise Assertionerror ("Could not determine the thre Ad ' s ID ') def raise_exc (self, Exctype): "" "raises the given exception type in the context of this thread" "" _async_ra Ise (Self._get_my_tid (), Exctype) def terminate (self): "" "raises systemexit in the context of the given thread, which sho Uld cause the thread to exit silently (unless caught) "" "Self.raise_exc (Systemexit)
Examples of Use:
>>> 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 >>&G T T.terminate () >>> t.join () outta here >>> t.isalive () False
Try it out, it's nice, but if there's a time.sleep () in the thread that's going to kill, it seems like it's not working properly, and I don't know what the real reason is. is already very strong. Ha ha.