3 volatile int headoffset, tailoffset;
6 pthread_mutexattr_t qlockattr;
10 #define QSIZE 1000000 //1 MB
12 void queueInit(void) {
13 /* Intitialize primary queue */
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);
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)
30 //Wait for tail to go past new start
31 while(tailoffset<=tmpoffset)
33 *((int *)(memory+headoffset))=-1;//safe because we left space
34 *((int*)memory)=size+sizeof(int);
35 return memory+sizeof(int);
37 while(headoffset<tailoffset&&tailoffset<=tmpoffset)
39 *((int*)(memory+headoffset))=size+sizeof(int);
40 return memory+headoffset+sizeof(int);
44 void movehead(int size) {
45 int tmpoffset=headoffset+size+sizeof(int);
46 if (tmpoffset>QSIZE) {
47 headoffset=size+sizeof(int);
50 pthread_cond_signal(&qcond);//wake the other thread up
54 while(tailoffset==headoffset) {
56 pthread_mutex_lock(&qlock);
57 if (tailoffset==headoffset)
58 pthread_cond_wait(&qcond, &qlock);
59 pthread_mutex_unlock(&qlock);
61 if (*((int *)(memory+tailoffset))==-1) {
62 tailoffset=0;//do loop
65 return memory+tailoffset+sizeof(int);
69 int tmpoffset=tailoffset+*((int *)(memory+tailoffset));