[Python] Pausing, unpausing, and stopping threads in python

Discussão em 'Python' iniciado por Stack, Junho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a program that has equivalents for another module's code.

    The module has it's own thread class, with the commands 'stop', and 'sleep_for'

    For example, using this module, you could do this:

    from fancyModule import *
    import time

    def yell():
    while True:
    print('HI!!!')

    mythread = Thread('HI!!!')
    time.sleep(3)
    mythread.stop()


    For my problem, I am making my own file, to be imported instead of the fancy one.

    I can use threading, multiprocessing, asyncio, or just about anything. The problem that I am running into, is that the users function can be just about anything, so I can't use events or flags. Is there anything I can do? Maybe by stopping the thread/process from the function? Here is what I have tried:

    class Thread:
    def __init__(self, callback, *arg):
    self.MYTHREAD = threading.Thread(target=callback, args=arg)
    self.MYLOCK = threading.Lock()
    self.MYTHREAD.start()
    def stop(self):
    self.MYLOCK.acquire()
    def sleep_for(self, duration, units=MSEC):
    self.MYLOCK.acquire()
    threading.Timer(duration * units, self.MYLOCK.release).start()


    Note that the thread is started when the thread is defined.

    As of right now I'm trying to acquire a lock, but I don't think that that is what a lock does. Is this even possible?

    Continue reading...

Compartilhe esta Página