Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/opentelemetry/util/_once.py: 44%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

16 statements  

1# Copyright The OpenTelemetry Authors 

2# SPDX-License-Identifier: Apache-2.0 

3 

4from collections.abc import Callable 

5from threading import Lock 

6 

7 

8class Once: 

9 """Execute a function exactly once and block all callers until the function returns 

10 

11 Same as golang's `sync.Once <https://pkg.go.dev/sync#Once>`_ 

12 """ 

13 

14 def __init__(self) -> None: 

15 self._lock = Lock() 

16 self._done = False 

17 

18 def do_once(self, func: Callable[[], None]) -> bool: 

19 """Execute ``func`` if it hasn't been executed or return. 

20 

21 Will block until ``func`` has been called by one thread. 

22 

23 Returns: 

24 Whether or not ``func`` was executed in this call 

25 """ 

26 

27 # fast path, try to avoid locking 

28 if self._done: 

29 return False 

30 

31 with self._lock: 

32 if not self._done: 

33 func() 

34 self._done = True 

35 return True 

36 return False