-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
7 additions
and
6 deletions.
There are no files selected for viewing
This file contains 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,16 +1,17 @@ | ||
import concurrent.futures | ||
import multiprocessing | ||
from collections.abc import Callable | ||
from typing import TypeVar | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
def run_with_timeout(task: Callable[[], T], timeout: int) -> T: | ||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: | ||
future = executor.submit(task) | ||
# Use multiprocessing to prevent a thread from blocking the main thread | ||
with multiprocessing.Pool(processes=1) as pool: | ||
async_result = pool.apply_async(task) | ||
try: | ||
# Wait at most 5 seconds for the function to complete | ||
result = future.result(timeout=timeout) | ||
# Wait at most timeout seconds for the function to complete | ||
result = async_result.get(timeout=timeout) | ||
return result | ||
except concurrent.futures.TimeoutError: | ||
except multiprocessing.TimeoutError: | ||
raise TimeoutError(f"Function timed out after {timeout} seconds") |