There are cases when we'd like to have a callback, but Postgres doesn't provide one. Fortunately, in some cases, there is still a way to do this.
When MemoryContext
is deleted or reset, you can use this as a "slingshot" to
inject your callback there.
Examples of such use:
- Upon
PostmasterContext
deletion, initialize the backend - When transaction is committed and visible to other backends,
TopTransactionContext
is reset. Transaction callbacks don't get us that far.
MemoryContextCallback *cb = MemoryContextAlloc(/* TargetMemoryContext */, sizeof(*cb));
cb->func = /* callback function */;
cb->arg = /* function argument */
MemoryContextRegisterResetCallback(/* TargetMemoryContext */, cb);
Caution
Newly registered callbacks will be called before those registered earlier, effectively reversing the order in which the callbacks are called.