Skip to main content

pg_shmem_init

Macro pg_shmem_init 

Source
macro_rules! pg_shmem_init {
    ($var:ident) => { ... };
    ($var:ident = $e:expr) => { ... };
}
Expand description

In order to store a type in Postgres Shared Memory, it must be passed to pg_shmem_init!() during _PG_init().

Additionally, the type must be a static global and also be #[derive(Copy, Clone)].

Types that allocate on the heap, such as String and Vec are not supported.

For complex data structures like vecs and maps, pgrx prefers the use of types from heapless.

Custom types need to also implement the PGRXSharedMemory trait.

Extensions that use shared memory must be loaded via postgresql.conf’s shared_preload_libraries configuration setting.

§Example

use pgrx::prelude::*;
use pgrx::{PgAtomic, PgLwLock, pg_shmem_init, PgSharedMemoryInitialization};
use std::sync::atomic::AtomicBool;

// Primitive types must be protected behind a `PgLwLock`.
static PRIMITIVE: PgLwLock<i32> = unsafe { PgLwLock::new(c"primitive") };

// Rust atomics can be used without locks, wrapped in a `PgAtomic`.
static ATOMIC: PgAtomic<AtomicBool> = unsafe { PgAtomic::new(c"atomic") };

#[pg_guard]
pub extern "C-unwind" fn _PG_init() {
    pg_shmem_init!(PRIMITIVE);
    pg_shmem_init!(ATOMIC);
}