Shared memory objects provide mechanisms to create and manage access to a memory region that is accessed concurrently by multiple tasks.
The osCreateSharedMemory function initializes a shared memory object. Shared memory may be created during system startup, from within an interrupt service routine, or by a running task. An optional name can be assigned during creation, which allows other tasks to locate and open the object using the osOpenSharedMemory function. Both creation and opening functions return a system-assigned handle used to uniquely identify the object. All subsequent operations on the shared memory region require this handle. When a shared memory object is no longer required, it should be closed using osCloseHandle. The object is deleted by the kernel only after all tasks that opened it have closed their respective handles. For more information, please refer to the System Objects Management section.
If shared memory functionality is not required, the OS_USE_SHARED_MEM constant can be set to 0 to minimize the final code size.
Upon the creation of a shared memory instance, a dedicated memory buffer is allocated. The base address of this buffer is returned during the creation or opening process. Additionally, the address associated with a specific handle can be retrieved at any time using the osGetSharedMemoryAddress function. This function is available only when the OS_GET_SH_MEM_ADDRESS_FUNC constant is set to 1.
Memory access synchronization can be implemented using three different methods, determined by the Mode parameter during object creation.
If the OS_IPC_PROTECT_MUTEX flag is used, the memory region is protected by a mutex object, which prevents priority inversion. This feature is enabled only if the OS_SH_MEM_PROTECT_MUTEX constant is set to 1. In scenarios where priority inversion is not a concern, the memory can be protected by an auto-reset event object by specifying the OS_IPC_PROTECT_EVENT flag.
To gain access to the shared memory, a task must call one of the system wait functions. Once the wait is satisfied, the task assumes ownership of the shared memory, ensuring that no other task can access the buffer simultaneously. Ownership is released by calling the osReleaseSharedMemory function. For detailed information on these synchronization primitives, refer to the Mutex and Event sections.
If the memory access operation is extremely brief, synchronization can be achieved by disabling interrupts using arLock and subsequently restoring them with arRestore. When using this method, the standard wait and osReleaseSharedMemory functions are not required.