Commit 7dab90c5 authored by Simon Sebastian Humpohl's avatar Simon Sebastian Humpohl
Browse files

Add parallel module

parent 52bcbe68
......@@ -47,3 +47,7 @@ Here you find decorators, functions and classes that help you implement caching
## qutil.io
User input related functions like `query_yes_no`.
## qutil.parallel
Functions and classes related to parallel execution i.e. multi-threading, multi-processing and asyncio.
There is a class for periodic callbacks from another thread `ThreadedPeriodicCallback`.
import threading
import time
class ThreadedPeriodicCallback:
"""Periodically call the given function. Dont forget to call start. You can change the period while it runs.
Be aware that your callback needs to be thread safe. This means you need to make sure that the state there is always
consistent.
Example:
>>> pcb = ThreadedPeriodicCallback(1., lambda: print('my function'))
>>> pcb.start()
>>> pcb.stop()
"""
def __init__(self, period: float, callback: callable):
self._stop = False
self.period = period
self.callback = callback
self.thread = threading.Thread(target=self._run)
def _run(self):
while not self._stop:
self.callback()
time.sleep(self.period)
def stop(self):
self._stop = True
self.thread.join()
def start(self):
self.thread.start()
def __del__(self):
self.stop()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment