From fe705ef6fc1d1b4b48aea94a1dd2835a6630dacf Mon Sep 17 00:00:00 2001 From: Michael Paquier Date: Wed, 1 Nov 2023 14:54:13 +0900 Subject: [PATCH] doc: Expand section related to LWLocks and shared memory The documentation includes a section describing how to define custom LWLocks in extensions using the shmem hooks. However, it has never mentioned the second, more flexible method based on the following routines: - LWLockNewTrancheId() to allocate a tranche ID. - LWLockRegisterTranche() to associate a name to a tranche ID. - LWLockInitialize() to initialize a LWLock with a tranche ID. autoprewarm.c is the only example of extension in the tree that allocates a LWLock this way. This commit adds some documentation about all that. While on it, a comment is added about the need of AddinShmemInitLock. This is required especially for EXEC_BACKEND builds (aka Windows, normally), as per a remark from Alexander, because backends can execute shmem initialization paths concurrently. Author: Aleksander Alekseev, Michael Paquier Discussion: https://postgr.es/m/CAJ7c6TPKhFgL+54cdTD9yGpG4+sNcyJ+N1GvQqAxgWENAOa3VA@mail.gmail.com --- doc/src/sgml/xfunc.sgml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml index 96ba95818c2..89116ae74c2 100644 --- a/doc/src/sgml/xfunc.sgml +++ b/doc/src/sgml/xfunc.sgml @@ -3428,6 +3428,29 @@ void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks) contrib/pg_stat_statements/pg_stat_statements.c in the PostgreSQL source tree. + + There is another, more flexible method of obtaining LWLocks. First, + allocate a tranche_id from a shared counter by + calling: + +int LWLockNewTrancheId(void) + + Next, each individual process using the tranche_id + should associate it with a tranche_name by calling: + +void LWLockRegisterTranche(int tranche_id, const char *tranche_name) + + It is also required to call LWLockInitialize once + per LWLock, passing the tranche_id as argument: + +void LWLockInitialize(LWLock *lock, int tranche_id) + + A complete usage example of LWLockNewTrancheId, + LWLockInitialize and + LWLockRegisterTranche can be found in + contrib/pg_prewarm/autoprewarm.c in the + PostgreSQL source tree. + To avoid possible race-conditions, each backend should use the LWLock AddinShmemInitLock when connecting to and initializing @@ -3451,6 +3474,13 @@ if (!ptr) } + + It is convenient to use shmem_startup_hook which allows + placing all the code responsible for initializing shared memory in one + place. When using shmem_startup_hook the extension + still needs to acquire AddinShmemInitLock in order to + work properly on all the supported platforms. + -- 2.39.5