-
Notifications
You must be signed in to change notification settings - Fork 1k
feat: new SafeThreadPoolExecutor for Ubuntu 24.04 upgrade #19263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yejianquan
merged 1 commit into
sonic-net:master
from
cyw233:change-to-new-multi-thread-utils
Jul 14, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,80 @@ | ||
| from concurrent.futures import Future, as_completed | ||
| from concurrent.futures.thread import ThreadPoolExecutor | ||
| from typing import Optional, List | ||
| import multiprocessing.pool | ||
| from multiprocessing.pool import ThreadPool | ||
| from typing import List | ||
|
|
||
|
|
||
| class SafeThreadPoolExecutor(ThreadPoolExecutor): | ||
| """An enhanced thread pool executor | ||
| class SafeThreadPoolExecutor: | ||
| """ | ||
| A thread pool executor that collects all AsyncResult objects and waits for their completion. | ||
|
|
||
| Example Usage: | ||
|
|
||
| with SafeThreadPoolExecutor(max_workers=len(duthosts)) as executor: | ||
| for duthost in duthosts: | ||
| executor.submit(example_func, duthost, localhost) | ||
|
|
||
| Everytime we submit a task, it will store the feature in self.features | ||
| On the __exit__ function, it will wait all the tasks to be finished, | ||
| And check any exceptions that are raised during the task executing | ||
| Behavior Summary: | ||
| 1. On instantiation, starts `max_workers` threads via ThreadPool. | ||
| 2. Each thread runs the submitted function (e.g., `example_func(arg1, arg2)`) in parallel. | ||
| 3. When the `with` block scope ends, execution moves to `__exit__`, where it blocks on each `AsyncResult.get()` | ||
| in turn to wait for all tasks to finish. | ||
| 4. If all threads succeed without raising, the pool is shut down cleanly. | ||
| 5. If any thread raises an exception, `.get()` re-raises that exception in the main thread. | ||
| """ | ||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
| self.features: Optional[List[Future]] = [] | ||
|
|
||
| def submit(self, __fn, *args, **kwargs): | ||
| f = super().submit(__fn, *args, **kwargs) | ||
| self.features.append(f) | ||
| return f | ||
| def __init__(self, max_workers, *args, **kwargs): | ||
| """ | ||
| Create a ThreadPool with `max_workers` threads and initialize an empty list to collect results. | ||
|
|
||
| Args: | ||
| max_workers: number of worker threads (maps to ThreadPool's `processes` parameter). | ||
| *args, **kwargs: ignored (only here to match ThreadPoolExecutor signature). | ||
| """ | ||
| self._pool = ThreadPool(processes=max_workers) | ||
| self._results: List["multiprocessing.pool.ApplyResult"] = [] | ||
|
|
||
| def submit(self, fn, *args, **kwargs): | ||
| """ | ||
| Schedule fn(*args, **kwargs) to run in a worker thread. | ||
| Returns an ApplyResult object whose .get() will return the result or re-raise any exception from the worker. | ||
| """ | ||
| # Wrap the user‐provided fn in a wrapper to catch any BaseException, and convert that BaseException into | ||
| # a regular RuntimeError so ThreadPool's "except Exception" block will catch and enqueue it. | ||
| def _wrapper(*fn_args, **fn_kwargs): | ||
| try: | ||
| return fn(*fn_args, **fn_kwargs) | ||
| except BaseException as be: | ||
| raise RuntimeError("Thread worker aborted: " + repr(be)) | ||
|
|
||
| async_res = self._pool.apply_async(_wrapper, args, kwargs) | ||
| self._results.append(async_res) | ||
| return async_res | ||
|
|
||
| def shutdown(self, wait=True): | ||
| """ | ||
| Stop accepting new tasks and optionally wait for running ones to finish. | ||
| """ | ||
| # Prevent new tasks | ||
| self._pool.close() | ||
| if wait: | ||
| # Wait for all tasks to finish | ||
| self._pool.join() | ||
|
|
||
| def __enter__(self): | ||
| """ | ||
| Support the "with" statement. | ||
| """ | ||
| return self | ||
|
|
||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| for future in as_completed(self.features): | ||
| # if exception caught in the sub-thread, .result() will raise it in the main thread | ||
| _ = future.result() | ||
| """ | ||
| Wait for each submitted task to complete and surface exceptions. | ||
| """ | ||
| for async_res in self._results: | ||
| # .get() will block until the task finishes, and re-raise any exception to the main thread. | ||
| async_res.get() | ||
|
|
||
| # Shut down the pool by close + join. | ||
| self.shutdown(wait=True) | ||
| # Returning False to ensure that any exception in the "with" statement is not suppressed. | ||
| return False |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Temporarily disable SAI validation for now as it will not be compatible with Ubuntu 24.04 due to the usage of
concurrent.futures. We will refactor the SAI validation and re-enable it later. Microsoft ADO to track the progress: 33758029