Last active
December 8, 2023 14:11
-
-
Save AndreFCruz/0c57b1bf8371d25a343c2956c77ee68d to your computer and use it in GitHub Desktop.
An executor that runs tasks on the main thread.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """An executor that runs tasks on the main thread. | |
| This can come in handy for debugging. For example, enables you to inspect and | |
| set breakpoints on the underlying task, which is not easily done when using | |
| separate threads. | |
| Usually one would use this executor when the user provided `--n-jobs=0`. | |
| """ | |
| import logging | |
| import concurrent.futures | |
| class MainThreadExecutor(concurrent.futures.Executor): | |
| """An executor that runs tasks on the main thread.""" | |
| def __init__(self, *args, **kwargs): | |
| logging.warning(f"MainThreadExecutor:: Ignoring args={args} and kwargs={kwargs}") | |
| self._shutdown = False | |
| def submit(self, fn, *args, **kwargs): | |
| if self._shutdown: | |
| raise RuntimeError("Cannot schedule new futures after shutdown") | |
| future = concurrent.futures.Future() | |
| try: | |
| result = fn(*args, **kwargs) | |
| future.set_result(result) | |
| except Exception as e: | |
| future.set_exception(e) | |
| return future | |
| def map(self, fn, *iterables, timeout=None, chunksize=1): | |
| return [ | |
| self.submit(fn, *args).result() | |
| for args in zip(*iterables) | |
| ] | |
| def shutdown(self, wait=True): | |
| self._shutdown = True | |
| if __name__ == "__main__": | |
| # Example usage: | |
| import threading | |
| def example_task(name): | |
| print(f"Executing task {name} on thread {threading.current_thread().name}") | |
| with MainThreadExecutor() as executor: | |
| results = list(executor.map(example_task, range(5))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment