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 if (headoffset<tailoffset) {
29 pthread_cond_signal(&qcond);//wake the other thread up
32 //Wait for tail to go past new start
33 if (tailoffset<=tmpoffset) {
34 pthread_cond_signal(&qcond);//wake the other thread up
37 *((int *)(memory+headoffset))=-1;//safe because we left space
38 *((int*)memory)=size+sizeof(int);
39 return memory+sizeof(int);
41 if (headoffset<tailoffset&&tailoffset<=tmpoffset) {
42 pthread_cond_signal(&qcond);//wake the other thread up
45 *((int*)(memory+headoffset))=size+sizeof(int);
46 return memory+headoffset+sizeof(int);
50 void movehead(int size) {
51 int tmpoffset=headoffset+size+sizeof(int);
52 if (tmpoffset>QSIZE) {
53 headoffset=size+sizeof(int);
56 pthread_cond_signal(&qcond);//wake the other thread up
60 while(tailoffset==headoffset) {
62 pthread_mutex_lock(&qlock);
63 if (tailoffset==headoffset)
64 pthread_cond_wait(&qcond, &qlock);
65 pthread_mutex_unlock(&qlock);
67 if (*((int *)(memory+tailoffset))==-1) {
68 tailoffset=0;//do loop
71 return memory+tailoffset+sizeof(int);
75 int tmpoffset=tailoffset+*((int *)(memory+tailoffset));