Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion threadpoolctl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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"
Expand All @@ -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:
#
Expand Down
Loading