Thread with python loading

Asked

Viewed 198 times

2

I’m trying to run two threads where one is an animation of loading, and the other a print, but when finished executing the thread work which is the print, the loading keeps running, I’d like it to finish as soon as the print is done

import itertools
import threading
import time
import sys

done = False

#here is the animation
def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\rloading ' + c)
        sys.stdout.flush()
        time.sleep(0.1)
    sys.stdout.write('\rDone!     ')

def work():
    print('\nexecutado, finalizando o loading')
    #long process here
    done = True

load = threading.Thread(target=animate)
load.start()
worker = threading.Thread(target=work)
worker.start()

1 answer

1


Your logic is right, in trying to finish one Thread using another, but there is a substantial error in the code, when you indicate within the work function that the done = True he will be True just inside the function, when I went to run your code, when debugging using prints When entering the work function it (the variable), it is true, but when leaving it returns to False. So what should be done is, do the function work() return the value of done = True, and out of function consume that value.

import itertools
import threading
import time
import sys

done = False

#here is the animation
def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\rloading ' + c)
        sys.stdout.flush()
        time.sleep(0.1)
    sys.stdout.write('\rDone!     ')

def work():
    print('\nexecutado, finalizando o loading')
    #long process here

    done = True

    return done # Aqui você retorna o valor

load = threading.Thread(target=animate)
load.start()
worker = threading.Thread(target=work)

done = work()  #Aqui você recebe o valor True

worker.start()

I didn’t work on the code, just two lines, so only with this fit it won’t have the output you want, but at least it worked as to finishing a thread with another thread.

  • Thank you very much brother, I was not seeing the error! :)

  • 1

    Beauty bro! When things like this happen, you can either check how it works using your IDE’s Debugger, or test how the code works line by line, initially printing all the dubious states.

  • thanks for the tip!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.