• Re: How to stop a specific thread in Python 2.7?

    From Stefan Ram@21:1/5 to marc nicole on Wed Sep 25 17:39:37 2024
    marc nicole <mk1853387@gmail.com> wrote or quoted:
    I want to know how to kill a specific running thread (say by its id)

    Killing or stopping a thread can cause data corruption and
    unpredictable behavior. It's better to use a more chill
    approach like setting a flag to let the thread know when to
    wrap it up and exit gracefully. If you really need to terminate
    something abruptly, go for a process instead of a thread.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Cameron Simpson@21:1/5 to marc nicole on Thu Sep 26 06:44:09 2024
    On 25Sep2024 19:24, marc nicole <mk1853387@gmail.com> wrote:
    I want to know how to kill a specific running thread (say by its id)

    for now I run and kill a thread like the following:
    # start thread
    thread1 = threading.Thread(target= self.some_func(), args=( ...,), ) >thread1.start()
    # kill the thread
    event_thread1 = threading.Event()
    event_thread1.set()

    I know that set() will kill all running threads, but if there was thread2
    as well and I want to kill only thread1?

    No, `set()` doesn't kill a thread at all. It sets the `Event`, and each
    thread must be checking that event regularly, and quitting if it becomes
    set.

    You just need a per-thred vent instead of a single Event for all the
    threads.

    Cheers,
    Cameron Simpson <cs@cskk.id.au>

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Lawrence D'Oliveiro@21:1/5 to Stefan Ram on Wed Sep 25 21:42:10 2024
    On 25 Sep 2024 17:39:37 GMT, Stefan Ram wrote:

    Killing or stopping a thread can cause data corruption and
    unpredictable behavior.

    Interesting that even the underlying POSIX thread-terminating call <https://manpages.debian.org/3/pthread_cancel.3.en.html> allows for the
    concept of “cancellation points”, so that threads can elect to only be terminated at well-defined points in their execution.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Cameron Simpson@21:1/5 to marc nicole on Thu Sep 26 11:06:03 2024
    On 25Sep2024 22:56, marc nicole <mk1853387@gmail.com> wrote:
    How to create a per-thread event in Python 2.7?

    Every time you make a Thread, make an Event. Pass it to the thread
    worker function and keep it to hand for your use outside the thread.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)