How does python kill a thread? Does python kill a thread?

Source: Internet
Author: User

How does python kill a thread? Does python kill a thread?

This requirement was recently encountered in the project:

I need a function, such as remotely connecting to a port and remotely reading files, but I have provided a limited amount of time. For example, if you haven't finished reading or the connection is successful in 4 seconds, I am not waiting. It is very likely that the other party has crashed or refused. In this way, you can do some tasks in batches without waiting for them all the time, which is a waste of time.

Based on my needs, I think of this method:

1. Execute in the main process, call a process execution function, and then sleep the main process. When the time is up, kill the process that executes the function.

Test 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()

The test takes only four seconds.

After some hard work, I thought of the join function. This function is used to wait for the end of a thread. If this function is not completed, it will block the currently running program. The key is that this parameter has an optional parameter: join ([timeout]): blocking the thread in the current context, wait until the thread that calls this method terminates or reaches the specified timeout (optional ).

I will not talk about the following code:

#! /Usr/bin/env python #-*-coding: UTF-8-*-''' author: cogbee time: 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: # // Add the task you want to do. If yes, set <span style = "font-family: Arial, Helvetica, sans-se Rif; "> self. thread_stop variable. </Span> [python] view plaincopy: view the CODE piece on the CODE to derive to my CODE piece 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 # Save all the readable items if file! = '': List. append (ip) print list if _ name _ = '_ main _': eachline = ['1. 1.1.1 ', '2017. 73.5.54 '] test (eachline)

The following is a piece of code that I wrote to kill a thread.

Since the python thread does not provide the abort method, share the following code to kill the thread:

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)

Example:

>>> 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

I tried it. It was good, but if there is time. sleep () in the thread to kill, it seems that the job is abnormal and I didn't find out the real reason. It is already very powerful. Haha.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.