from __future__ import annotations
import logging
from contextlib import contextmanager
from contextvars import ContextVar
from functools import partial, wraps
from multiprocessing.pool import Pool, ThreadPool
from threading import Lock, Thread
from typing import Any, Callable, Iterable, Iterator, Literal, TypeVar
from ..utils.check.errclass import CifRuntimeError, CifTypeError, CifValueError
V = TypeVar("V")
T = TypeVar("T")
__all__ = ["thread", "multicore", "AutoThreads"]
# Log records emitted by the task currently running in this thread,
# None when the thread is not running a task with captured logs
_task_records: ContextVar[list[logging.LogRecord] | None] = ContextVar(
"_task_records", default=None
)
_capture_lock = Lock()
_emit_lock = Lock()
_capture_users = 0
class _CaptureFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
records = _task_records.get()
if records is None:
return True
# The filter is called once per handler, store the record only once
if not getattr(record, "_cif_captured", False):
setattr(record, "_cif_captured", True)
records.append(record)
return False
_capture_filter = _CaptureFilter()
@contextmanager
def _capturing_logs() -> Iterator[None]:
global _capture_users
# Filters are attached to the handlers of the root logger, since the
# filters of a logger are not applied to the records of its children.
# Handlers added while capturing is active are not covered.
with _capture_lock:
_capture_users += 1
for handler in logging.getLogger().handlers:
handler.addFilter(_capture_filter)
try:
yield
finally:
with _capture_lock:
_capture_users -= 1
if _capture_users == 0:
for handler in logging.getLogger().handlers:
handler.removeFilter(_capture_filter)
def _flush_logs(
records: list[logging.LogRecord],
parent: list[logging.LogRecord] | None,
) -> None:
# Called from a task that is itself captured: hand the records over
# to it, they will be emitted when the outermost task is flushed
if parent is not None:
parent.extend(records)
return
# A record is emitted as a block, so that other threads cannot get
# in between. Handler.handle does not check the handler level.
handlers = logging.getLogger().handlers
with _emit_lock:
for record in records:
for handler in handlers:
if record.levelno >= handler.level:
handler.handle(record)
def _run_captured(call: Callable[[Any], T], arg: Any):
records: list[logging.LogRecord] = []
token = _task_records.set(records)
try:
return call(arg), records, None
except Exception as exc:
return None, records, exc
finally:
_task_records.reset(token)
def _use_pool(
func: Callable[[V], T],
kind: Literal["thread", "multicore"],
processes: int | None = None,
unpack: bool = False,
ordered_logs: bool = False,
) -> Callable[[Iterable[V]], Iterable[T]]:
if kind == "thread":
PoolClass = ThreadPool
elif kind == "multicore":
PoolClass = Pool
else:
raise CifValueError("'kind' argument should be 'thread' or 'multicore'")
def call(arg: Any) -> T:
return func(*arg) if unpack else func(arg)
@wraps(func)
def pool_func(arg: Iterable[V], chunksize: int | None = None) -> Iterable[T]:
if not isinstance(arg, Iterable):
raise CifTypeError(
f"function '{func.__name__}' has been decorated with the '{kind}' "
"decorator. Its argument must be iterable."
)
# Pool threads do not inherit the context of the caller, so the
# buffer of an enclosing captured task is fetched here. Nested pools
# are always captured, otherwise their logs would bypass the capture.
parent = _task_records.get()
if kind == "thread" and (ordered_logs or parent is not None):
results = []
error = None
with _capturing_logs(), PoolClass(processes) as pool:
# imap yields in input order as soon as results are ready.
# All tasks are drained even after a failure, to keep their
# logs, and the first error is raised at the end.
for result, records, exc in pool.imap(
partial(_run_captured, call), arg, chunksize or 1
):
_flush_logs(records, parent)
if exc is None:
results.append(result)
elif error is None:
error = exc
if error is not None:
raise error
return results
with PoolClass(processes) as pool:
if unpack:
return pool.starmap(func, arg, chunksize) # type: ignore
else:
return pool.map(func, arg, chunksize)
return pool_func
[docs]
def thread(
func: Callable[[V], T],
processes: int | None = None,
unpack: bool = False,
ordered_logs: bool = False,
) -> Callable[[Iterable[V]], Iterable[T]]:
"""Decorate a function to be called in threads with multiple arguments
.. warning::
If the :bash:`unpack` argument is False (default), the decorated function must
take exactly one argument.
Args:
func (callable (V) -> T):
Function to be parallelised with threads.
processes (int, optional):
Number of threads to use, if processes is None then the number
returned by os.process_cpu_count() is used. Defaults to None.
unpack (bool, optional):
Unpack the arguments when calling th decorated function.
If unpack is False :bash:`func([a, b])` returns :bash:`[func(a), func(b)]`
If unpack is True :bash:`func([a, b])` returns :bash:`[func(*a), func(*b)]`
Defaults to False.
ordered_logs (bool, optional):
Hold back the messages sent through :bash:`logging` by each call
and print them as one block per call, in the order of the
arguments. Output written with :bash:`print` is not affected.
If several calls fail, the first error in argument order is raised
after all calls have finished. Defaults to False.
Returns:
callable (Iterable[V]) -> T:
Function parallelised on threads, takes a chunksize argument
.. code-block:: python
>>> @thread
... def foo(x):
... return 2*x
...
>>> foo([2, 5, 4, 8])
[4, 10, 8, 16]
With :bash:`unpack=True`
.. code-block:: python
>>> @thread(unpack=True)
... def foo(a, b):
... return a + b
...
>>> foo([(1, 2), (3, 4), (5, 6)])
[3, 7, 11]
"""
return _use_pool(func, "thread", processes, unpack, ordered_logs)
[docs]
def multicore(
func: Callable[[V], T],
processes: int | None = None,
unpack: bool = False,
) -> Callable[[Iterable[V]], Iterable[T]]:
"""Decorate a function to be called in threads with multiple arguments
.. note::
Due to pickling limitations, this decorator can not be used at the
decorated function definition, and must be called afterwrad.
.. warning::
If the :bash:`unpack` argument is False (default), the decorated function must
take exactly one argument.
Args:
func (callable (V) -> T):
Function to be parallelised on multiple cores.
processes (int, optional):
Number of threads to use, if processes is None then the number
returned by os.process_cpu_count() is used. Defaults to None.
unpack (bool, optional):
Unpack the arguments when calling th decorated function.
If unpack is False :bash:`func([a, b])` returns :bash:`[func(a), func(b)]`
If unpack is True :bash:`func([a, b])` returns :bash:`[func(*a), func(*b)]`
Defaults to False.
Returns:
callable (Iterable[V]) -> T:
Function parallelised on multiple cores, takes a chunksize argument
.. code-block:: python
>>> def foo(x):
... return 2*x
...
>>> parallel_foo = multicore(foo)
>>> parallel_foo([2, 5, 4, 8])
[4, 10, 8, 16]
With :bash:`unpack=True`
.. code-block:: python
>>> def foo(a, b):
... return a + b
...
>>> parallel_foo = multicore(foo, unpack=True)
>>> parallel_foo([(1, 2), (3, 4), (5, 6)])
[3, 7, 11]
"""
return _use_pool(func, "multicore", processes, unpack)
[docs]
class AutoThreads:
"""A group of threads that can be used as a context manager for automatic
joining.
With a context manager:
.. code-block:: python
>>> with AutoThreads() as threads:
... threads.start(foo, 1)
... threads.start(bar, 2, flag=True)
... # Some other code
... threads.start(bar, 24, flag=False)
...
>>> # Implicit join here
Without a context manager:
.. code-block:: python
>>> threads = AutoThreads()
>>> threads.start(foo, 1)
>>> threads.start(bar, 2, flag=True)
>>> # Some other code
>>> threads.start(bar, 24, flag=False)
>>> threads.join() # Explicit join here
Args:
timeout : float, optional
Default timeout in seconds, by default None
"""
def __init__(self, timeout: float | None = None) -> None:
self._threads: list[Thread] = []
self._timeout = timeout
self._context_manager = False
self._terminated = False
def __repr__(self) -> str:
names = [thread.name for thread in self._threads]
return f"<AutoThreads {names}>"
def start(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
"""Call a function in a new thread, positional and keyword arguments are
passed to the function.
Args:
func (callable):
Function to be called in a new thread.
args (tuple):
Positional arguments to be passed to the function.
kwargs (dict):
Keyword arguments to be passed to the function.
"""
if self._context_manager and self._terminated:
raise CifRuntimeError("AutoThreads object already exited")
thread = Thread(target=func, args=args, kwargs=kwargs)
thread.start()
self._threads.append(thread)
def join(self, timeout: float | None = None) -> None:
"""Join all threads.
Args:
timeout (float, optional):
Timeout in seconds overrides the default timeout, by default None
"""
timeout = timeout if timeout is not None else self._timeout
for thread in self._threads:
thread.join(timeout)
def __enter__(self) -> AutoThreads:
if self._threads:
raise CifRuntimeError("AutoThreads object already contains some threads")
self._context_manager = True
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.join()
self._terminated = True