Blocking Read Shared Multi-Queue

<< prev end

This example shows how to do a blocking read of a Shared Multi-Queue using the Shared Memory Arena library.

You can leave the last two programs running and now in addition run
./smq_blocking_read
As you can see it appears to run no differently than the last read program, but in this case we are not calling sleep and we are using the system in a very efficient way, signaling the program the instant when there is a new entry to read.

Looking at the Source

From /ref examples/tutorial/smq_blocking_read.c

First we include some header files:

#include <unistd.h> /* for usleep() */
#include <signal.h> /* for signal() */
#include <shm_arena.h> /* for Shared Memory Arena Library */
static int running = 1;
static smq_t q;
static void catcher(int sig)
{
printf("catch signal %d\n", sig);
/* Unblock the current or next smq_rdlock() call. */
running = 0;
}
int main(void)
{
signal(SIGINT, catcher);
q = smq_get(NULL, sizeof(int), 22, "q_count", O_CREAT);
if(!q)
{
printf("smq_get() failed\n");
return 1;
}
while(running)
{
int num;
/* block until there is at least 1 in the queue */
num = smq_rdlock(q, 1);
while(num > 0)
{
int *ptr;
ptr = smq_read(q);
printf("%d ", *ptr);
fflush(stdout);
num--;
}
}
/* Because smq_unblock_rdlock() spawns a thread to release the
* blocking smq_rdlock() and that thread must make mutex calls, we
* need to call smq_delete(q) to wait for thread to finish, to avoid
* deadlocking the multi-queue. smq_delete(q) only cleans up the
* local process data and not the shared memory data. */
return 0;
}

Shared Multi-Queues are good for real-time data feeds, when you don't want to miss any data.

<< prev end


Shared Memory Arena version RC-0.0.25