diff --git a/threadpoolctl.py b/threadpoolctl.py index eba58089..92a1d311 100644 --- a/threadpoolctl.py +++ b/threadpoolctl.py @@ -1148,6 +1148,8 @@ def __init__(self, controller, *, limits=None, user_api=None): self._original_info = dict( zip(self._controller.lib_controllers, self._controller.info()) ) + # The undo log must not include libraries we did not change. + self._restore_info = {} self._set_threadpool_limits() def __enter__(self): @@ -1167,7 +1169,8 @@ def wrap(cls, controller, *, limits=None, user_api=None): def restore_original_limits(self): """Set the limits back to their original values""" - for lib_controller, original_info in self._original_info.items(): + # Undo in reverse order: multiple controllers can share native state. + for lib_controller, original_info in reversed(self._restore_info.items()): lib_controller.set_num_threads(original_info["num_threads"]) # Alias of `restore_original_limits` for backward compatibility @@ -1212,6 +1215,8 @@ def get_original_num_threads(self): def _set_threadpool_limits(self): """Change the maximal number of threads in selected thread pools.""" if self._limits is None: + # limits=None is also used to explicitly save and restore a snapshot. + self._restore_info.update(self._original_info) return took_control = False @@ -1230,6 +1235,7 @@ def _set_threadpool_limits(self): continue if num_threads is not None: + self._restore_info[lib_controller] = self._original_info[lib_controller] if ( type(lib_controller) is not OpenBLASController or lib_controller.threading_layer == "openmp" @@ -1247,6 +1253,7 @@ def _set_threadpool_limits(self): # this thread later became the controlling thread during # restoration, it might restore the wrong value. self._original_info.pop(lib_controller, None) + self._restore_info.pop(lib_controller, None) elif isinstance(result, _THIS_THREAD_TOOK_CONTROL): # Now that we took control: #