异步通知
A mechanism is provided to make asynchronous notifications to the main interpreter thread. These notifications take the form of a function pointer and a void pointer argument.
int Py_AddPendingCall
(int (func)(void \), void arg*)
Schedule a function to be called from the main interpreter thread. On success, 0
is returned and func is queued for being called in the main thread. On failure, -1
is returned without setting any exception.
When successfully queued, func will be eventually called from the main interpreter thread with the argument arg. It will be called asynchronously with respect to normally running Python code, but with both these conditions met:
on a bytecode boundary;
with the main thread holding the global interpreter lock (func can therefore use the full C API).
func must return 0
on success, or -1
on failure with an exception set. func won’t be interrupted to perform another asynchronous notification recursively, but it can still be interrupted to switch threads if the global interpreter lock is released.
This function doesn’t need a current thread state to run, and it doesn’t need the global interpreter lock.
To call this function in a subinterpreter, the caller must hold the GIL. Otherwise, the function func can be scheduled to be called from the wrong interpreter.
警告
This is a low-level function, only useful for very special cases. There is no guarantee that func will be called as quick as possible. If the main thread is busy executing a system call, func won’t be called before the system call returns. This function is generally not suitable for calling Python code from arbitrary C threads. Instead, use the PyGILState API.
在 3.9 版更改: If this function is called in a subinterpreter, the function func is now scheduled to be called from the subinterpreter, rather than being called from the main interpreter. Each subinterpreter now has its own list of scheduled calls.
3.1 新版功能.