From 892c661f4ced5ce47a713031987cbc153a98798c Mon Sep 17 00:00:00 2001
From: Aleksander Alekseev <aleksander@timescale.com>
Date: Tue, 23 May 2023 13:32:40 +0300
Subject: [PATCH v4] Clarify the "38.10.10. Shared Memory and LWLocks" section

Prior to this commit the documentation showed an example of acquiring shared
memory and LWLocks from an extension without much clarification why the
extension needs to acquire AddinShmemInitLock. Clarify this and also document
the existence shmem_startup_hook.

While on it also mention the existence of LWLockNewTrancheId() and
LWLockRegisterTranche().

Aleksander Alekseev, reviewed by Michael Paquier

Discussion: https://postgr.es/m/CAJ7c6TPKhFgL%2B54cdTD9yGpG4%2BsNcyJ%2BN1GvQqAxgWENAOa3VA%40mail.gmail.com
---
 doc/src/sgml/xfunc.sgml | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)

diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 96ba95818c..2884ca4742 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3424,9 +3424,18 @@ void RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
      to get a pointer to this array.
     </para>
     <para>
-     An example of a <literal>shmem_request_hook</literal> can be found in
-     <filename>contrib/pg_stat_statements/pg_stat_statements.c</filename> in the
-     <productname>PostgreSQL</productname> source tree.
+     When necessary, an unique tranche ID can be allocated:
+<programlisting>
+int LWLockNewTrancheId(void)
+</programlisting>
+     Also a dynamic name in the lookup table of the current process can be assigned to the tranche:
+<programlisting>
+void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
+</programlisting>
+    A complete usage example of <function>LWLockNewTrancheId</function> and
+    <function>LWLockRegisterTranche</function> can be found in
+    <filename>contrib/pg_prewarm/autoprewarm.c</filename> in the
+    <productname>PostgreSQL</productname> source tree.
     </para>
     <para>
      To avoid possible race-conditions, each backend should use the LWLock
@@ -3451,6 +3460,18 @@ if (!ptr)
 }
 </programlisting>
     </para>
+    <para>
+    It is convenient to use <literal>shmem_startup_hook</literal> which allows
+    placing all the code responsible for initializing shared memory in one place.
+    When using <literal>shmem_startup_hook</literal> the extension still needs
+    to acquire <function>AddinShmemInitLock</function> in order to work properly
+    on all the supported platforms.
+    </para>
+    <para>
+     A complete example of allocating shared memory and LWLocks can be found in
+     <filename>contrib/pg_stat_statements/pg_stat_statements.c</filename> in the
+     <productname>PostgreSQL</productname> source tree.
+    </para>
    </sect2>
 
    <sect2 id="xfunc-addin-wait-events">
-- 
2.42.0

