Change tabbing for everything....
[IRC.git] / Robust / src / Runtime / DSTM / interface / queue.c
1 #include "queue.h"
2
3 volatile int headoffset, tailoffset;
4 char * memory;
5 pthread_mutex_t qlock;
6 pthread_mutexattr_t qlockattr;
7 pthread_cond_t qcond;
8
9 #define QSIZE 2048 //2 KB
10
11 void queueInit(void) {
12   /* Intitialize primary queue */
13   headoffset=0;
14   tailoffset=0;
15   memory=malloc(QSIZE+sizeof(int)); //leave space for -1
16   pthread_mutexattr_init(&qlockattr);
17   pthread_mutexattr_settype(&qlockattr, PTHREAD_MUTEX_RECURSIVE_NP);
18   pthread_mutex_init(&qlock, &qlockattr);
19   pthread_cond_init(&qcond, NULL);
20 }
21
22 void * getmemory(int size) {
23   int tmpoffset=headoffset+size+sizeof(int);
24   if (tmpoffset>QSIZE) {
25     //Wait for tail to go past end
26     tmpoffset=size+sizeof(int);
27     if (headoffset<tailoffset) {
28       pthread_cond_signal(&qcond); //wake the other thread up
29       return NULL;
30     }
31     //Wait for tail to go past new start
32     if (tailoffset<=tmpoffset) {
33       pthread_cond_signal(&qcond); //wake the other thread up
34       return NULL;
35     }
36     *((int *)(memory+headoffset))=-1; //safe because we left space
37     *((int*)memory)=size+sizeof(int);
38     return memory+sizeof(int);
39   } else {
40     if (headoffset<tailoffset&&tailoffset<=tmpoffset) {
41       pthread_cond_signal(&qcond); //wake the other thread up
42       return NULL;
43     }
44     *((int*)(memory+headoffset))=size+sizeof(int);
45     return memory+headoffset+sizeof(int);
46   }
47 }
48
49 void movehead(int size) {
50   int tmpoffset=headoffset+size+sizeof(int);
51   if (tmpoffset>QSIZE) {
52     headoffset=size+sizeof(int);
53   } else
54     headoffset=tmpoffset;
55   pthread_cond_signal(&qcond); //wake the other thread up
56 }
57
58 void * gettail() {
59   while(tailoffset==headoffset) {
60     //Sleep
61     pthread_mutex_lock(&qlock);
62     if (tailoffset==headoffset)
63       pthread_cond_wait(&qcond, &qlock);
64     pthread_mutex_unlock(&qlock);
65   }
66   if (*((int *)(memory+tailoffset))==-1) {
67     tailoffset=0; //do loop
68   }
69
70   return memory+tailoffset+sizeof(int);
71 }
72
73 void inctail() {
74   int tmpoffset=tailoffset+*((int *)(memory+tailoffset));
75   if (tmpoffset>QSIZE)
76     tailoffset=0;
77   else
78     tailoffset=tmpoffset;
79 }
80
81 void predealloc() {
82   free(memory);
83 }
84