Atomic Segment Creation and Initialization

<< prev next >>

From the source file examples/tutorial/atomic_get.c

#include <unistd.h> /* for usleep() */
#include <errno.h>
#include <shm_arena.h> /* for Shared Memory Arena Library */
int main(void)
{
int *ptr;
int created = 0; /* bool */
const char *SEG_NAME = "my count";
size_t seg_size = sizeof(int);
/* Get exclusive access to the shared memory arena. Because this is
* the first Shared Memory Arena API call, his also automatically
* creates this local process's arena object using the default
* shared memory arena file. */
{
printf("Failed to get arena lock\n");
return 1;
}
/* First check if the segment is already exists. */
errno = 0;
ptr = (int *) sm_connect(SHM_UNKNOWN_SIZE, SEG_NAME);
if(!ptr && !errno)
{
errno = 0;
/* The segment does not exist so we create it */
ptr = (int *) sm_create(seg_size, SEG_NAME);
if(ptr)
{
/* and initialize it, */
*ptr = 0;
created = 1;
}
}
else if(!errno)
seg_size = sm_size(ptr);
if(!ptr)
{
printf("failed to create segment \"%s\"\n", SEG_NAME);
return 1;
}
/* all in an atomic manner. Release exclusive access. */
if(ptr)
{
if(created)
printf("Created shared memory segment \"%s\" of size %zu\n",
SEG_NAME, seg_size);
else
printf("Shared memory segment \"%s\" of size %zu already exists\n",
SEG_NAME, seg_size);
}
return 0;
}

Using sm_arena_wrlock(), or shm_arena_wrlock() you can make many arena operations inter-process and intra-process thread safe.

The library libshm_arena provides two levels of inter-process shared read-write locks, one outer lock to protect the whole arena file and an optional per segment read-write lock. Both read-write locks are inter-process locks, meaning they do their work between all processes that connect to a particular arena file. The outer arena file read-write lock is required to block all but one process from allocating or freeing segments in the arena any given time.

The functions sm_wrlock(), sm_rdlock(), shm_wrlock(), and shm_rdlock() automatically acquire an arena read lock before acquiring the corrisponding segment lock, if it was not explicitly gotten with sm_arena_wrlock(), sm_arena_rdlock(), shm_arena_wrlock(), or shm_arena_rdlock(). Like-wise the sm_unlock(), and shm_unlock(), automatically release the arena read lock if it was not explicitly gotten with sm_arena_wrlock(), sm_arena_rdlock(), shm_arena_wrlock(), or shm_arena_rdlock().

<< prev next >>


Shared Memory Arena version RC-0.0.25