Obtain a block of allocated named memory

The benefit of named memory is that several UDRs can access it. Therefore, UDRs can cache data for sharing between UDRs executing in different contexts.

To use named memory, UDRs that need to access it must take the following steps:
  • One UDR needs to allocate the named-memory block with mi_named_alloc() or mi_named_zalloc().

    This named-memory block must have a name that will be known to all UDRs that need to access the block. It must also have a memory duration that is sufficient for the required lifetime of the cached data. The UDR that allocates the named memory can access the data from the address that mi_named_alloc() or mi_named_zalloc() returns. However, once this UDR completes, the local copy of this address is deallocated.

  • Any UDR that needs to access the data in the named-memory block can specify the name and memory duration of the memory block to mi_named_get().

    The mi_named_get() function returns the address of the named-memory block. The UDR can use this address to access the desired data within the named memory.

For example, suppose a UDR named initialize() allocates a named-memory block named cache_blk with the following mi_named_alloc() call:
mi_integer *blk_ptr;
mi_integer status;
...
status = mi_named_alloc(sizeof(mi_integer), "cache_blk",
   PER_STMT_EXEC, &blk_ptr);

switch( status )
{
   case MI_ERROR:
      mi_db_error_raise(NULL, MI_EXCEPTION,
         "mi_named_alloc for cache_blk failed.");
      break;

   case MI_NAME_ALREADY_EXISTS:
      break;

   case MI_OK:
      *blk_ptr = 0;
      break;

   default:
      mi_db_error_raise(NULL, MI_EXCEPTION,
         "Invalid mi_named_alloc status for cache_blk");
}
If another UDR, for example, some_task(), needs to access the integer in cache_blk, it can use the mi_named_get() function, as the following code fragment shows:
mi_integer *blk_ptr;
mi_integer status;
...
status = mi_named_get("cache_blk", PER_STMT_EXEC, &blk_ptr);

switch( status )
{
   case MI_ERROR:
      mi_db_error_raise(NULL, MI_EXCEPTION,
         "mi_named_get for cache_blk failed.");
      break;

   case MI_NO_SUCH_NAME:
      /* maybe need to call mi_named_alloc() here */
      ...
      break;

   case MI_OK:
      if ( *blk_ptr > 0 )
         *blk_ptr++;
      break;

   default:
      mi_db_error_raise(NULL, MI_EXCEPTION,
         "Invalid mi_named_alloc status for cache_blk");
}
If some_task() successfully obtains the address of the cache_blk named-memory block (status is MI_OK), it increments the cached integer.
Important: The preceding code fragment does not handle concurrency issues that result from multiple UDRs trying to access the cache_blk named memory at the same time. For more information, see Handling concurrency issues.