Nurislom Rakhmatullaev
Nurislom Rakhmatullaev

Reputation: 315

Multithread continue to work, after it is stopped (Python

I wrote some code with while loop in it. Then I put it on theread. When I want to stop thread I will change while loop's condition and it will stop. But when I want to continue after stoppping, I can't do it.

I tried to make it recursive. But it takes processor time. How I can do it properly?

class Some_class():
    def __init__(self):
        self.while_condition = True
        self.mythread = Thread(target=self.do_trade)
    
    def start(self):
        if self.while_condition = False:
            self.while_condition = True
        else: 
            self.mythread.start()
    
    def stop(self):
        self.while_condition = False
    
    def do_action(self):
        while(self.while_condition):
            print("thread is working")
            time.sleep(5)
        print("action stopped")
        self.do_action()
obj = Some_class()

I expected the output:

thread is working

thread is working

after obj.stop()

action stopped

then obj.start() will continue

thread is working

thread is working

Upvotes: 0

Views: 71

Answers (1)

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

There is a lot of wrong things in your code, check the correct code below and find out what was wrong:

Note, threads can only start one time and can not be restarted, so you start new thread every time

from threading import Thread
import time

class Some_class():
    def __init__(self):
        self.while_condition = True

    def start(self):
        self.while_condition = True
        Thread(target=self.do_action).start()

    def stop(self):
        self.while_condition = False

    def do_action(self):
        while(self.while_condition):
            print("thread is working")
            time.sleep(5)
        print("action stopped")
obj = Some_class()
obj.start()
time.sleep(10)
obj.stop()
time.sleep(5)
print('restarting thread')
obj.start()

output:

thread is working
thread is working
action stopped
restarting thread
thread is working
thread is working
thread is working

Upvotes: 2

Related Questions