Miscellaneous Utilities¶
call_once
¶
call_once(func)
Decorator that ensures a function is called only once during the lifetime of a process, across all threads.
If multiple threads call the decorated function simultaneously, only one thread (the "leader") will execute the function. Other threads will wait for the leader to finish and then return the same result.
If the function raises an exception, the same exception will be re-raised in all threads.
Example
The expensive_initialization_function below will be called only once,
even if it is called from multiple threads concurrently.
Since you may want the function to be unit-tested and wrapping it in a decorator may make things awkward, you can wrap it after the definition:
Parameters:
-
–func¶The function to be called once.
Returns:
-
–
A wrapper function that ensures
funcis executed only once.