1

I normally starts the thread using the following command,

threading.Thread(target=function_name).start()

Is there any way to pause it like

threading.Thread(target=name).wait()

and resume is like

threading.Thread(target=name).set()

Deepak pal
  • 61
  • 8
  • Does this answer your question? [Thread that I can pause and resume?](https://stackoverflow.com/questions/33640283/thread-that-i-can-pause-and-resume) – Maritn Ge Dec 26 '20 at 18:00
  • I also saw that but unfortunately, I do not think that is the best way when you want to stop for example a function which is processing a large amount of data instead of while looping – AmaanK Dec 26 '20 at 18:03
  • you need to set signals by using a variable, so the thread checks the variable every so on and either stops, waits or starts depending on the value of the variable. – coderoftheday Dec 27 '20 at 01:41

2 Answers2

2

How about check this project. This project meets all your requirements. Python's built-in threading module does not support play and pause functionality for now.

So to install that modules: pip install pythreadworker

After installation here is a example:

from worker import Worker  # We import the Worker to create thread

def some_long_running_task(foo, bar, tee="foo"):
    do_random_long_stuff()
    # ...

if __name__ == '__main__':
    # to make a thread we initialise Worker or somewhat so called the Thread of threading module
    thread = Worker(some_long_running_task)  # remember just pass the function without execution parenthesis

    # Now to start thread while also supplying arguments, we call start method
    thread.start("bar", bar="foo", tee=123)

    # To pause a the thread we use pause method
    thread.pause()

    # To resume it we use resume method
    thread.resume()

    # To use the Thread.join Worker class, use the join method
    thread.join()

    # And to kill it we use 
    thread.stop()

But do remember while using that if you are using time.sleep then you will have to replace it with worker.sleep

so for example you import code is

from time import sleep

replace it with

from worker import sleep

Hope this helps.

AmaanK
  • 1,032
  • 5
  • 25
  • thank you for the suggestion! I gone through the project but the usage is quite confusing.. for example, If I want to execute a single function in a thread like this `threading.Thread(target=function_name).start()`, then what will be the scenario in this project ? – Deepak pal Dec 26 '20 at 19:22
  • I hope this might help you now – AmaanK Dec 27 '20 at 04:00
1

The threading module has a Semaphore, which might help. If there isn't something already built-in to the threading module, you could try using a Tkinter semaphore variable specific to each thread, and have the thread check its semaphore while in some polling loop.

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32