Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 84103
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T21:52:41+00:00 2026-05-10T21:52:41+00:00

Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?

  • 0

Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T21:52:42+00:00Added an answer on May 10, 2026 at 9:52 pm

    It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:

    • the thread is holding a critical resource that must be closed properly
    • the thread has created several other threads that must be killed as well.

    The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.

    For example:

    import threading  class StoppableThread(threading.Thread):     """Thread class with a stop() method. The thread itself has to check     regularly for the stopped() condition."""      def __init__(self,  *args, **kwargs):         super(StoppableThread, self).__init__(*args, **kwargs)         self._stop_event = threading.Event()      def stop(self):         self._stop_event.set()      def stopped(self):         return self._stop_event.is_set() 

    In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.

    There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.

    The following code allows (with some restrictions) to raise an Exception in a Python thread:

    def _async_raise(tid, exctype):     '''Raises an exception in the threads with id tid'''     if not inspect.isclass(exctype):         raise TypeError("Only types can be raised (not instances)")     res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(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(ctypes.c_long(tid), None)         raise SystemError("PyThreadState_SetAsyncExc failed")  class ThreadWithExc(threading.Thread):     '''A thread class that supports raising an exception in the thread from        another thread.     '''     def _get_my_tid(self):         """determines this (self's) thread id          CAREFUL: this function is executed in the context of the caller         thread, to get the identity of the thread represented by this         instance.         """         if not self.is_alive(): # Note: self.isAlive() on older version of Python             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          # TODO: in python 2.6, there's a simpler way to do: self.ident          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.          If the thread is busy in a system call (time.sleep(),         socket.accept(), ...), the exception is simply ignored.          If you are sure that your exception should terminate the thread,         one way to ensure that it works is:              t = ThreadWithExc( ... )             ...             t.raise_exc( SomeException )             while t.isAlive():                 time.sleep( 0.1 )                 t.raise_exc( SomeException )          If the exception is to be caught by the thread, you need a way to         check that your thread has caught it.          CAREFUL: this function is executed in the context of the         caller thread, to raise an exception in the context of the         thread represented by this instance.         """         _async_raise( self._get_my_tid(), exctype ) 

    (Based on Killable Threads by Tomer Filiba. The quote about the return value of PyThreadState_SetAsyncExc appears to be from an old version of Python.)

    As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.

    A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 75k
  • Answers 75k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer The solution for this was to have a script that… May 11, 2026 at 2:45 pm
  • added an answer I usually don't implement things in advance unless I need… May 11, 2026 at 2:45 pm
  • added an answer To get the Hardware specs for the Doc connector you… May 11, 2026 at 2:45 pm

Related Questions

I am working through some of the exercises in The C++ Programming Language by
In my C# program, I have a thread that represents a running test, which
Please pardon my C#.Net newbie status. If this is obvious and I missed it
So I got a 64 bit virtual machine running x64 Windows Server 2003 Standard

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.