Is there a way to pause and restart a thread or kill a thread and start it again?

35 Views Asked by At

The project I am working on involves threading using a while loop which web scrapes stock prices from a website and plots this on a matplotlib graph.

I am now trying enable the user to change the stock they chose, but in order to do so I need to stop/pause/kill the thread so that the user can enter the new stock and then restart/start a new thread with the new chosen stock.

I am struggling to figure out how I can start the thread again or continue it as I have managed to 'pause' it by using a flag in the while loop of the thread that stops it from actually displaying anything but I am assuming this is bad practice because the thread is still active.

Here is the code for how I have paused the thread and what I tried to restart it:

stock_thread = threading.Thread(target=fetch_stock_price) #The thread itself
while True:

      if not stop_thread: #The while loop within the thread to see if it has been flagged to stop
        ...
else:
        break
if stock_thread.is_alive():
      stock_thread.join() #I know that this doesn't work and I cannot figure out what to do instead
    else:
      stock_thread.start()

In summary, the program has a button which generates a graph for the stock and a button which changes the stock. The button that generates the graph is bound to a command which starts the thread using stock_thread.start() and the change stock button should stop/kill/pause the thread using:

global stop_thread
    stop_thread = True

and then recall the same command bounded to the generate graph button to restart the thread.

I am getting an error saying that the a thread can only be started once, is there a way to work around this in the context of my project?

Thanks

0

There are 0 best solutions below