3 volatile int headoffset, tailoffset;
6 pthread_mutexattr_t qlockattr;
9 #define QSIZE 2048 //2 KB
11 void queueInit(void) {
12 /* Intitialize primary queue */
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);
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
31 //Wait for tail to go past new start
32 if (tailoffset<=tmpoffset) {
33 pthread_cond_signal(&qcond); //wake the other thread up
36 *((int *)(memory+headoffset))=-1; //safe because we left space
37 *((int*)memory)=size+sizeof(int);
38 return memory+sizeof(int);
40 if (headoffset<tailoffset&&tailoffset<=tmpoffset) {
41 pthread_cond_signal(&qcond); //wake the other thread up
44 *((int*)(memory+headoffset))=size+sizeof(int);
45 return memory+headoffset+sizeof(int);
49 void movehead(int size) {
50 int tmpoffset=headoffset+size+sizeof(int);
51 if (tmpoffset>QSIZE) {
52 headoffset=size+sizeof(int);
55 pthread_cond_signal(&qcond); //wake the other thread up
59 while(tailoffset==headoffset) {
61 pthread_mutex_lock(&qlock);
62 if (tailoffset==headoffset)
63 pthread_cond_wait(&qcond, &qlock);
64 pthread_mutex_unlock(&qlock);
66 if (*((int *)(memory+tailoffset))==-1) {
67 tailoffset=0; //do loop
70 return memory+tailoffset+sizeof(int);
74 int tmpoffset=tailoffset+*((int *)(memory+tailoffset));