smq_blocking_read.c
1 
26 #include <unistd.h> /* for usleep() */
27 #include <signal.h> /* for signal() */
28 #include <shm_arena.h> /* for Shared Memory Arena Library */
29 
30 static int running = 1;
31 static smq_t q;
32 
33 
34 static void catcher(int sig)
35 {
36  printf("catch signal %d\n", sig);
37 
38  /* Unblock the current or next smq_rdlock() call. */
40  running = 0;
41 }
42 
43 int main(void)
44 {
45  signal(SIGINT, catcher);
46 
47  q = smq_get(NULL, sizeof(int), 22, "q_count", O_CREAT);
48  if(!q)
49  {
50  printf("smq_get() failed\n");
51  return 1;
52  }
53 
54  while(running)
55  {
56  int num;
57 
58  /* block until there is at least 1 in the queue */
59  num = smq_rdlock(q, 1);
60 
61  while(num > 0)
62  {
63  int *ptr;
64  ptr = smq_read(q);
65  printf("%d ", *ptr);
66  fflush(stdout);
67  num--;
68  }
69 
70  smq_unlock(q);
71  }
72 
73  /* Because smq_unblock_rdlock() spawns a thread to release the
74  * blocking smq_rdlock() and that thread must make mutex calls, we
75  * need to call smq_delete(q) to wait for thread to finish, to avoid
76  * deadlocking the multi-queue. smq_delete(q) only cleans up the
77  * local process data and not the shared memory data. */
78  smq_delete(q);
79 
80  return 0;
81 }
smq_t smq_get(shm_arena_t arena, size_t element_size, int q_length, const char *name, int flags)
get a Shared Multi-Queue object
Definition: smq.c:358
int smq_rdlock(smq_t q, int num)
acquire Shared Multi-Queue read-lock
Definition: smq.c:881
int smq_unblock_rdlock(smq_t q)
unblock a smq_rdlock() call if needed
Definition: smq.c:1027
int smq_delete(smq_t q)
delete the local Shared Multi-Queue object
Definition: smq.c:810
struct smq * smq_t
shared multi-queue object
Definition: shm_arena.h:196
int smq_unlock(smq_t q)
release Shared Multi-Queue read or write lock
Definition: smq.c:1102
void * smq_read(smq_t q)
read the next entry from the Shared Multi-Queue
Definition: smq.c:1262

Shared Memory Arena version RC-0.0.25