Threading-> Stopping

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tuvas

    #1

    Threading-> Stopping

    Is there a way to stop a thread with some command like t.stop()? Or any
    other neat way to get around it? Thanks!

  • David  Wahler

    #2
    Re: Threading-> Stopping

    Tuvas wrote:[color=blue]
    > Is there a way to stop a thread with some command like t.stop()? Or any
    > other neat way to get around it? Thanks![/color]

    Sadly, no. While Java and many other programming languages have an
    interrupt() primitive, Python does not. You can approximate this by
    using a global variable to tell the thread when to stop, for example:

    shutdown = False

    class MyThread(Thread ):
    def run(self):
    while not shutdown:
    # do whatever

    def kill_thread():
    shutdown = True

    There's no general way to wake up a thread that's blocked--you have to
    satisfy the condition that's causing it to block. If it's waiting for
    input from a Queue, you have to push a dummy value down it to wake up
    the thread and give it a chance to check the shutdown flag. If it's
    blocking to do I/O, you'll have to use select() and provide a timeout
    value to check the flag periodically.

    -- David

    Comment

    • Tuvas

      #3
      Re: Threading-> Stopping

      Thanks!

      Comment

      • Antoon Pardon

        #4
        Re: Threading-> Stopping

        Op 2005-11-04, Tuvas schreef <tuvas21@gmail. com>:[color=blue]
        > Is there a way to stop a thread with some command like t.stop()? Or any
        > other neat way to get around it? Thanks![/color]

        What do you mean with stop? Pauze it or make it finish.

        In the latter case, if you really want it you could use the following.
        It requires ctypes. It also wont stop a thread while it is in a C
        extention. In that case the exception will be raised when it returns
        from the extention.

        import os
        import ctypes
        from time import sleep
        from random import randint


        class TimeOut(Excepti on):
        pass

        class Alarm(Exception ):
        pass

        import threading

        class Xthread(threadi ng.Thread):

        def start(self):
        self.__original _run = self.run
        self.run = self.__run
        threading.Threa d.start(self)

        def __run(self):
        self.__thrd_id = threading._get_ ident()
        try:
        self.__original _run()
        finally:
        self.run = self.__original _run

        def raize(self, excpt):
        Nr = ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf.__thrd_id, ctypes.py_objec t(excpt))
        while Nr > 1:
        ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf.__thrd_id, None)
        sleep(0.1)
        Nr = ctypes.pythonap i.PyThreadState _SetAsyncExc(se lf.__thrd_id, ctypes.py_objec t(excpt))

        def alarm(self, tm):
        alrm = threading.Timer (tm, self.raize, (TimeOut,))
        alrm.start()
        return alrm

        if __name__ == "__main__":

        class Continue(Xthrea d):

        def run(self):

        self.id = os.getpid()
        print self.id, "Begin"
        i = 0
        try:
        for _ in xrange(randint( 0,20)):
        for e in xrange(4 * 100000):
        i = i + e
        print self.id, "Finished"
        except Alarm:
        print self.id, "Interupted "

        lst = [Continue() for _ in xrange(10)]

        for T in lst:
        T.start()

        try:
        sleep(10)
        finally:
        for T in lst:
        T.raize(Alarm)

        Comment

        • Alan Kennedy

          #5
          Re: Threading-&gt; Stopping

          [Tuvas][color=blue]
          > Is there a way to stop a thread with some command like t.stop()? Or any
          > other neat way to get around it? Thanks![/color]

          Good question.

          And one that gets asked so often, I ask myself why it isn't in the FAQ?

          The official home of the Python Programming Language


          It really should be in the FAQ. Isn't that what FAQs are for?

          Maybe the FAQ needs to be turned into a wiki?

          --
          alan kennedy
          ------------------------------------------------------
          email alan: http://xhaus.com/contact/alan

          Comment

          • Bengt Richter

            #6
            Re: Threading-&gt; Stopping

            On Mon, 07 Nov 2005 13:49:35 +0000, Alan Kennedy <alanmk@hotmail .com> wrote:
            [color=blue]
            >[Tuvas][color=green]
            >> Is there a way to stop a thread with some command like t.stop()? Or any
            >> other neat way to get around it? Thanks![/color]
            >
            >Good question.
            >
            >And one that gets asked so often, I ask myself why it isn't in the FAQ?
            >
            >http://www.python.org/doc/faq/library.html
            >
            >It really should be in the FAQ. Isn't that what FAQs are for?
            >
            >Maybe the FAQ needs to be turned into a wiki?
            >[/color]
            Maybe when really good answers to questions get posted, we could edit it
            down to a final version candidate that we all agree on, and when agreed,
            make the final post with a tag line that google will recognize and that
            can be a tag line for python newsgroup gems.

            Sort of like a wiki-within-newsgroup in effect. E.g., "Tim Peters" site:python.org
            gets a lot of interesting stuff. Likewise Martelli, though the volume is daunting
            either way (140,000 & 32,400 resp ;-)

            What about "python-newsgroup-faq" site:python.org ? If we avoid the tag line in all but
            finalized posts, that plus some additional search-narrowing via google would probably
            be pretty effective. But this is a social engineering problem more than technical ;-)

            BTW, would such a thing appropriately be defined in a process PEP?

            Regards,
            Bengt Richter

            Comment

            Working...