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?
#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


Messages In This Thread
RE: Anyway to stop a thread and continue it? - by DeaD_EyE - Mar-18-2024, 10:53 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Stop/continue While loop block Moris526 68 26,913 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,829 Jan-31-2020, 11:08 AM
Last Post: DeaD_EyE
  Is Event.set() the preferred way to stop a thread? svetlanarosemond 5 3,950 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