start of new file
[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     if (headoffset<tailoffset) {
29       pthread_cond_signal(&qcond);//wake the other thread up
30       return NULL;
31     }
32     //Wait for tail to go past new start
33     if (tailoffset<=tmpoffset) {
34       pthread_cond_signal(&qcond);//wake the other thread up
35       return NULL;
36     }
37     *((int *)(memory+headoffset))=-1;//safe because we left space
38     *((int*)memory)=size+sizeof(int);
39     return memory+sizeof(int);
40   } else {
41     if (headoffset<tailoffset&&tailoffset<=tmpoffset) {
42       pthread_cond_signal(&qcond);//wake the other thread up
43       return NULL;
44     }
45     *((int*)(memory+headoffset))=size+sizeof(int);
46     return memory+headoffset+sizeof(int);
47   }
48 }
49
50 void movehead(int size) {
51   int tmpoffset=headoffset+size+sizeof(int);
52   if (tmpoffset>QSIZE) {
53     headoffset=size+sizeof(int);
54   } else
55     headoffset=tmpoffset;
56   pthread_cond_signal(&qcond);//wake the other thread up
57 }
58
59 void * gettail() {
60   while(tailoffset==headoffset) {
61     //Sleep
62     pthread_mutex_lock(&qlock);
63     if (tailoffset==headoffset)
64       pthread_cond_wait(&qcond, &qlock);
65     pthread_mutex_unlock(&qlock);
66   }
67   if (*((int *)(memory+tailoffset))==-1) {
68     tailoffset=0;//do loop
69   }
70
71   return memory+tailoffset+sizeof(int);
72 }
73
74 void inctail() {
75   int tmpoffset=tailoffset+*((int *)(memory+tailoffset));
76   if (tmpoffset>QSIZE)
77     tailoffset=0;
78   else
79     tailoffset=tmpoffset;
80 }
81
82 void predealloc() {
83   free(memory);
84 }
85