assigns workerID to the workerTR
[IRC.git] / Robust / src / Runtime / oooJava / trqueue.c
1 #include "trqueue.h"
2 #include "stdlib.h"
3 #include "stdio.h"
4 #include "mlp_lock.h"
5 #include <pthread.h>
6 #include "structdefs.h"
7 #include "RuntimeConflictResolver.h"
8
9 extern volatile int numWorkSchedWorkers;
10
11 struct trQueue * queuelist=NULL;
12 pthread_mutex_t queuelock;
13
14 //0 would mean sucess
15 //1 would mean fail
16 //since if we reach SIZE, we will stop operation, it doesn't matter
17 //that we overwrite the element in the queue
18 void enqueueTR(struct trQueue *q, void * ptr) {
19   unsigned int head=q->head+1;
20   if (head&TRSIZE)
21     head=0;
22
23   while (head==q->tail)
24     sched_yield();
25   
26   q->elements[head] = ptr;
27   BARRIER();
28   q->head=head;
29 }
30
31 void * dequeueTR(struct trQueue *q) {
32   unsigned int tail=q->tail;
33   if(q->head==tail)
34     return NULL;
35
36   tail++;
37   if(tail & TRSIZE)
38     tail =  0;
39
40   void * ptr = q->elements[tail];
41   q->tail=tail;
42   return ptr;
43 }
44
45 void createTR() {
46   struct trQueue *ptr=NULL;
47   int myid;
48   pthread_mutex_lock(&queuelock);
49   ptr=queuelist;
50   if (ptr!=NULL) {
51     queuelist=ptr->next;
52   } else {
53     myid=numWorkSchedWorkers;
54     numWorkSchedWorkers++;
55   }  
56   pthread_mutex_unlock(&queuelock);
57   if (ptr==NULL) {
58     pthread_t thread;
59     pthread_attr_t nattr;
60     pthread_attr_init(&nattr);
61     pthread_attr_setdetachstate( &nattr, PTHREAD_CREATE_DETACHED);
62     ptr=malloc(sizeof(struct trQueue));
63     ptr->head=0;
64     ptr->tail=0;
65     ptr->id=myid;
66     ptr->allHashStructures=createAndFillMasterHashStructureArray();
67     int status=pthread_create( &thread, NULL, workerTR, (void *) ptr);
68     if (status!=0) {printf("ERROR\n");exit(-1);}
69     pthread_attr_destroy(&nattr);
70   }
71   TRqueue=ptr;
72 }
73
74 void returnTR() {
75   //return worker thread to pool
76   pthread_mutex_lock(&queuelock);
77   TRqueue->next=queuelist;
78   queuelist=TRqueue;
79   pthread_mutex_unlock(&queuelock);
80   //release our worker thread
81   TRqueue=NULL;
82 }