_once.py 941 B

123456789101112131415161718192021222324252627282930313233343536
  1. # Copyright The OpenTelemetry Authors
  2. # SPDX-License-Identifier: Apache-2.0
  3. from collections.abc import Callable
  4. from threading import Lock
  5. class Once:
  6. """Execute a function exactly once and block all callers until the function returns
  7. Same as golang's `sync.Once <https://pkg.go.dev/sync#Once>`_
  8. """
  9. def __init__(self) -> None:
  10. self._lock = Lock()
  11. self._done = False
  12. def do_once(self, func: Callable[[], None]) -> bool:
  13. """Execute ``func`` if it hasn't been executed or return.
  14. Will block until ``func`` has been called by one thread.
  15. Returns:
  16. Whether or not ``func`` was executed in this call
  17. """
  18. # fast path, try to avoid locking
  19. if self._done:
  20. return False
  21. with self._lock:
  22. if not self._done:
  23. func()
  24. self._done = True
  25. return True
  26. return False