[issue39660] Contextvars: Optional callbacks on state change

Leonard Lausen report at bugs.python.org
Thu Feb 20 17:23:29 EST 2020


Leonard Lausen <leonard at lausen.nl> added the comment:

Consider a `lib = ctypes.CDLL(lib_path, ctypes.RTLD_LOCAL)` which provides APIs `lib.compute`, `lib.set_state` and a Python interface wrapping both in `def compute`, `def set_state`. Let's assume `lib.set_state` sets a thread-local state in the library implementation and further  that the behaviour of `lib.compute` depends on the last call to `lib.set_state`. 

Users of the Python interface may call `set_state` and `compute` concurrently in coroutines. Thereby one coroutine may change the state in the library, prior to another coroutine calling `compute`. This leads to a wrong result.

If `set_state` and `compute` were pure python functions, `contextvars` could be used to implement set_state and provide context-local state.

Is there any existing API that can be used to call `lib.set_state` on context changes? If so, please let me know. If not, would it make sense to extend `contexvars` to allow users to configure that `lib.set_state` is called on context change?

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39660>
_______________________________________


More information about the Python-bugs-list mailing list