RefLib

Reference library for AI

Back

postgresql_16:6.1.10.10 Shared Memory and LWLocks

PostgreSQL 16 > Server Programming > Extending SQL > C-Language Functions > Shared Memory and LWLocks

Add-ins can reserve LWLocks and an allocation of shared memory on server startup. The add-in's shared library must be preloaded by specifying it in (see guc-shared-preload-libraries). The shared library should register a shmem_request_hook in its _PG_init function. This shmem_request_hook can reserve LWLocks or shared memory. Shared memory is reserved by calling: void RequestAddinShmemSpace(int size) from your shmem_request_hook.

LWLocks are reserved by calling: void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks) from your shmem_request_hook. This will ensure that an array of num_lwlocks LWLocks is available under the name tranche_name. Use GetNamedLWLockTranche to get a pointer to this array.

An example of a shmem_request_hook can be found in contrib/pg_stat_statements/pg_stat_statements.c in the PostgreSQL source tree.

To avoid possible race-conditions, each backend should use the LWLock AddinShmemInitLock when connecting to and initializing its allocation of shared memory, as shown here: static mystruct *ptr = NULL; if (!ptr) { bool found; LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE); ptr = ShmemInitStruct("my struct name", size, &found); if (!found) { initialize contents of shmem area; acquire any requested LWLocks using: ptr->locks = GetNamedLWLockTranche("my tranche name"); } LWLockRelease(AddinShmemInitLock); }

Back