Python Forum
Anyway to stop a thread and continue it?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Anyway to stop a thread and continue it?
#1
Hi all,

I am using the threading module to run a while loop as a thread which scrapes stock information off of Yahoo Finance and appends it to a csv file parallel to functions which plot this information on a graph.

The issue is, the user should be able to leave the graph page (in which the thread stops doing what it's doing) to access other parts of the program and then potentially enter this section again and the thread should restart (not continue from where it left off).

My initial thought was to just kill the thread and create it again but this doesn't work as threads can only be started once and cannot be killed.

I have seen online that it may be possible to create another instance of the thread and start this but I don't believe this will work in the context of my project as this would mean I would have to iterate variable names and start new threads each time which is one, outside my level of expertise and two, not very practical.

Basically, I was wondering if there is a way to pause a thread or 'kill' it to stop what it's doing and then restart it later on if called again. I have read online about threading events but they don't make much sense to me. I have tried to use a flagging variable which is set to False initially and changes to True when I want the thread to stop but this doesn't actually kill the thread and instead just runs a while loop in the background with no output and just slows down the entire program.

stock_thread.start() # Initially start the thread
  def goMenu(self):

    stop_thread = True
stop_thread = False # To continue the thread
while len(stock_symbol) > 0:
      
  if not stop_thread:
      #code that does what i mentioned
I am fairly new to programming and any help would be much appreciated Smile
Reply
#2
You really need to post your code. If your thread has loop you can do this
while len(stock_symbol) > 0 and not stop_thread:
    # code that runs in thread
But if the thread is doing one thing that takes a long time to finish, you are out of luck. Have you thought about using processes?
Reply
#3
Example with a queue:

import time
from random import randint
from queue import Queue
from threading import Thread


def fake_feed():
    """
    Generator function which yields
    endless values from 0 to 255.
    """
    while True:
        time.sleep(1)
        yield randint(0, 255)


def feed_consumer(feed_gen, queue):
    """
    This function consumes the yielded values from
    feed_gen and put them into the queue.
    """
    for value in feed_gen:
        queue.put(value)


def worker(queue):
    """
    Worker function, which just print the objects from queue.
    """
    while value := queue.get():
        print(value)


print("Creating queue")
queue = Queue()
print("Calling fake_feed")
feed_gen = fake_feed()

print("Creating consumer_thread")
consumer_thread = Thread(target=feed_consumer, args=(feed_gen, queue))
print("Creating worker_thread")
worker_thread = Thread(target=worker, args=(queue,))

print("Starting both threads")
consumer_thread.start()
worker_thread.start()
But it depends on your code and a queue is not the only thing, which can be used for synchronization.
Beside queue, you could use Lock, RLock, Condition Objects, Semaphore, Event Objects, Timer Objects and Barrier Objects.

Often it's easier to do this tasks with asyncio, if there is a good library and if you know asyncio. Otherwise, should stick with the threading approach until you understand asyncio.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Stop/continue While loop block Moris526 68 25,430 Mar-28-2021, 09:21 PM
Last Post: Larz60+
  Error SQLite objects created in a thread can only be used in that same thread. binhduonggttn 3 15,580 Jan-31-2020, 11:08 AM
Last Post: DeaD_EyE
  Is Event.set() the preferred way to stop a thread? svetlanarosemond 5 3,833 Jul-17-2018, 08:14 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020