How to create a method that pause and one that resumes a Thread?

1

The following script shows the x variable every 3 seconds, while the xx class running on a thread increases the value of x every second. I would like, when the value of x reaches 13, the thread where the xx class is being executed would stop.

from threading import Thread
from time import sleep

class xx(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global x
        while True:
            x+=1
            sleep(1)

    def stop(self):
        #O que botar aqui para parar a execução da thread?

    def play(self):
        #O que botar aqui para iniciar a thread depois de pausada?



x=0

instx=xx()
instx.start()

while True:
    sleep(3)
    print(x)
    if x==13:
        instx.stop()

But I do not know what to put in the stop (self) and play (self) methods to pause and resume thread execution. How can I do this?

    
asked by anonymous 11.02.2017 / 22:40

1 answer

3

There is not much magic possible, as well as some shared data care between threads.

In your child thread, the only code running is what is in the "run" function - and all other methods actually are code executed on the main thread, which creates the child threads.

So, anything you want to do that has effects on what is running on the child thread, has to be done in the code that is run in the thread -

Once you have a while True: , that is, a code that loops in a row of this while you should either check, or call a function that checks, changed data in the main function.

With this, and with the use of Queue, Locks, Events and Semaphores, described in link you can control two-way communication effectively between a main and a secondary thread, or between the main thread and a pool of coordinated secondary threas.

In particular, "Lock" objects can be "the right way" to do what you want to do with the "stop" and "play" methods there. But to respond in a simple way, what would be done would be to configure an object of type "Event" - it is something very simple of the module threading, that has a call wait that blocks, and only returns execution when the object is activated with the call to .set() , on some other thread.

from threading import Thread
from threading import Event
from time import sleep

class xx(Thread):
    def __init__(self):
        self._active = Event()
        self._active.set()
        Thread.__init__(self)

    def run(self):
        global x
        while True:
            self._active.wait()
            x+=1
            sleep(1)

    def stop(self):
        self.active.clear()

    def play(self):
        self.active.set()
    
13.02.2017 / 03:42