Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping a thread once condition matches

I want to trigger upfunction and stop when it writes 3 in the filename. Basically I want to stop a thread once the condition is met as shown below.

def getstatus():
    fh = open(filename,'r')
    return fh.read()

def  upfunction(arg):

    for i in range(arg):
        print ("backup running")
        print(getstatus())
        target = open(filename, 'w')
        target.write(str(i))
        sleep(1)



if __name__ == "__main__":
    thread = Thread(target = upfunction, args = (10, ))
    thread.start()
    print(getstatus())
    while getstatus() != "3":
        print("NOT 3 ")
        sleep(0.5)
        continue


    thread.stop()
    print("thread finished...exiting")

It shows

AttributeError: 'Thread' object has no attribute 'stop'

Please see me as newbie to python. Any help will be highly appreciated

like image 416
Prem Avatar asked Oct 23 '25 15:10

Prem


2 Answers

'Thread' object has no attribute 'stop' is helpful answer from python interpretator to you

You should place thread termination condition to upfunction.

    def  upfunction(arg):
        i = 0
        while getstatus() != "3":
            print ("backup running")
            print(getstatus())
            target = open(filename, 'w')
            target.write(str(i))
            i += 1
            sleep(1)

if __name__ == "__main__":
    thread = Thread(target = upfunction, args = (10, ))
    thread.start()
    print(getstatus())
    print("thread finished...exiting")
like image 116
Lex Hobbit Avatar answered Oct 26 '25 03:10

Lex Hobbit


you can just use threading deamon method to kill this new thread.

thread.start()
thread.deamon()

when the main threads ends this custom threads also dies .so there is no need of that.

like image 42
rishav Avatar answered Oct 26 '25 05:10

rishav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!