Copyright (c) Hyperion Entertainment and contributors.

Exec Named Memory

From AmigaOS Documentation Wiki
Jump to navigation Jump to search

Introduction

In a multi-tasking environment, it is often desirable to be able to share resources between two more more different Tasks or Processes. This can be done by passing memory pointers, but this is difficult since there is no defined "protocol" for this.

Exec V51 introduces a new concept called named memory. Instead of having to pass a pointer around, you decide on a name for your memory and have others (or yourself) access this memory by it's name. In addition, named memory can be organized into different namespaces. This allows for the same name to exist in different namespaces. All names in the same namespace must be unique.

The "resident" Namespace

One namespace is predefined with a special functionality: resident. This namespace and it's objects will be restored after reboot through ColdStart().

To ensure data integrity, it is possible to have the memory block automatically checksummed. The checksum is validated after reboot. If checksumming is enabled and the stored checksum and newly computed checksums match, the block is available to subsequent FindNamedMemory() calls. Otherwise, the block is discarded. If no checksumming is enabled for the block, the application must ensure data integrity.

Creating Named Memory

Named memory is first created using the AllocNamedMemory() function.

struct MySharedData {
  uint32 value;
  BOOL flag;
  uint8 eggs[12];
};
 
uint32 error;
 
APTR mem = IExec->AllocNamedMemoryTags(sizeof(struct MySharedData), NULL, "MySharedData",
  ANMT_Error, &error,
  TAG_END);
 
if (mem == NULL)
  IDOS->Printf("Allocation failed, error code %lu\n", error);

In this example, the global namespace is being used and the name of the memory is MySharedData.

Sharing Named Memory

Freeing Named Memory

Named memory should be freed when no longer in use. Any Task or Process may attempt to free named memory although it is advisable to have the same entity free it that created it.

BOOL success = IExec->FreeNamedMemory(NULL, "MySharedData");
 
if (!success)
  IDOS->Printf("MySharedData cannot be freed\n");

The boolean return value needs to be checked to verify whether the memory is now free or not. It is possible another Task or Process has a lock on the named memory at the same time it is being freed. This is why it is so important to establish a protocol when using shared memory.

To be documented

UpdateNamedMemory()
AttemptNamedMemory()
FindNamedMemory()
UnlockNamedMemory()
ScanNamedMemory()
LockNamedMemory()