Advertisement
Guest User

qlock.h

a guest
Dec 12th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include <stdlib.h>
  2.  
  3. struct msg {
  4.         struct msg *next;
  5. };
  6.  
  7. struct queue {
  8.         struct msg *head;
  9.         struct msg *tail;
  10.         int lock;
  11. };
  12.  
  13. #define LOCK(q) while (__sync_lock_test_and_set(&(q)->lock,1)) {}
  14. #define UNLOCK(q) __sync_lock_release(&(q)->lock);
  15.  
  16. static inline struct queue *
  17. qinit(void)
  18. {
  19.         struct queue *q = calloc(1, sizeof(*q));
  20.         return q;
  21. }
  22.  
  23. static inline int
  24. push(struct queue *q, struct msg *m)
  25. {
  26.         LOCK(q)
  27.         if (q->tail) {
  28.                 q->tail->next = m;
  29.                 q->tail = m;
  30.         } else {
  31.                 q->head = q->tail = m;
  32.         }
  33.         UNLOCK(q)
  34.  
  35.         return 0;
  36. }
  37.  
  38. static inline struct msg *
  39. pop(struct queue *q)
  40. {
  41.         struct msg *m;
  42.  
  43.         LOCK(q)
  44.         m = q->head;
  45.         if (m) {
  46.                 q->head = m->next;
  47.                 if (q->head == NULL) {
  48.                         q->tail = NULL;
  49.                 }
  50.                 m->next = NULL;
  51.         }
  52.         UNLOCK(q)
  53.  
  54.         return m;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement