38434dc61c8a14e6f736df9ad8085ec6f8c2a13f
[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
10 #define QSIZE 1000000 //1 MB
11
12 void queueInit(void) {
13   /* Intitialize primary queue */
14   headoffset=0;
15   tailoffset=0;
16   memory=malloc(QSIZE+sizeof(int));//leave space for -1
17   pthread_mutexattr_init(&qlockattr);
18   pthread_mutexattr_settype(&qlockattr, PTHREAD_MUTEX_RECURSIVE_NP);
19   pthread_mutex_init(&qlock, &qlockattr);
20   pthread_cond_init(&qcond, NULL);
21 }
22
23 void * getmemory(int size) {
24   int tmpoffset=headoffset+size+sizeof(int);
25   if (tmpoffset>QSIZE) {
26     //Wait for tail to go past end
27     tmpoffset=size+sizeof(int);
28     while(headoffset<tailoffset)
29       ;
30     //Wait for tail to go past new start
31     while(tailoffset<tmpoffset)
32       ;
33     *((int *)(memory+headoffset))=-1;//safe because we left space
34     *((int*)memory)=size+sizeof(int);
35     return memory+sizeof(int);
36   } else {
37     while(headoffset<tailoffset&&tailoffset<tmpoffset)
38       ;
39      *((int*)(memory+headoffset))=size+sizeof(int);
40     return memory+headoffset+sizeof(int);
41   }
42 }
43
44 void movehead(int size) {
45   int tmpoffset=headoffset+size+sizeof(int);
46   if (tmpoffset>QSIZE) {
47     headoffset=size+sizeof(int);
48   } else
49     headoffset=tmpoffset;
50   pthread_cond_signal(&qcond);//wake the other thread up
51 }
52
53 void * gettail() {
54   while(tailoffset==headoffset) {
55     //Sleep
56     pthread_mutex_lock(&qlock);
57     if (tailoffset==headoffset)
58       pthread_cond_wait(&qcond, &qlock);
59     pthread_mutex_unlock(&qlock);
60   }
61   if (*((int *)(memory+tailoffset))==-1) {
62     tailoffset=0;//do loop
63   }
64
65   return memory+tailoffset+sizeof(int);
66 }
67
68 void inctail() {
69   int tmpoffset=tailoffset+*((int *)(memory+tailoffset));
70   if (tmpoffset>QSIZE)
71     tailoffset=0;
72   else
73     tailoffset=tmpoffset;
74 }
75
76 void predealloc() {
77   free(memory);
78 }
79