void *producer(){ extern semaphore mutex, full, empty; extern int size; int data; while(1){ data=randint(1001); //printf("wait empty=%d\n",empty); wait(&empty); //printf("wait mutex=%d\n",mutex); wait(&mutex); //cs //printf("producer CS. number=%d, mutex=%d,empty=%d,full=%d\n",data,mutex,empty,full); printf("mutex=%d,empty=%d\n",mutex,empty); addtoQueue(&q,data); //end cs signal(&mutex); signal(&full); } }
/***************************** *********FLOW THREAD********** *****************************/ void *yourFlow(void* arg) { //variables //struct timeval curTime; struct flow curFlow = *(struct flow *)arg; double arv = (double)curFlow.arrival_time/10; double trans = (double)curFlow.trans_time/10; //sleep until arrival time usleep(curFlow.arrival_time * 1E5F); printf("Flow %2d arrives: arrival time (%.2f), transmission time (%.1f), priority (%2d). \n",curFlow.id, interval(), trans, curFlow.priority); //if no thread transmitting then transmit if(!trans_thread) { //set transmitting id variable to current flows id (mutex protected) pthread_mutex_lock(&transmit); trans_thread = curFlow.id; pthread_mutex_unlock(&transmit); //sleep for transmission time printf("Flow %2d starts its transmission at time %.2f. \n", curFlow.id, interval()); usleep(curFlow.trans_time* 1E5F); printf("Flow %2d finishes its transmission at time %.2f. \n", curFlow.id, interval()); } //add to queue else { //add to queue (mutex protected) pthread_mutex_lock(&queue_mutex); addtoQueue(curFlow); pthread_mutex_unlock(&queue_mutex); //wait for this flow to be flagged to transmit, while waiting print the id of the flow were waiting on printf("Flow %2d waits for the finish of flow %2d. \n", curFlow.id, trans_thread); int tmp = trans_thread; while(trans_thread != curFlow.id) { if(tmp != trans_thread && trans_thread != curFlow.id) { tmp = trans_thread; printf("Flow %2d waits for the finish of flow %2d. \n", curFlow.id, trans_thread); } } //once flagged transmit pthread_mutex_lock(&transmit); trans_thread = curFlow.id; pthread_mutex_unlock(&transmit); printf("Flow %2d starts its transmission at time %.2f. \n", curFlow.id, interval()); usleep(curFlow.trans_time* 1E5F); printf("Flow %2d finishes its transmission at time %.2f. \n", curFlow.id, interval()); } //crit sec passed removing from queue (mutex protected) pthread_mutex_lock(&transmit); //if no items are queue'd set transmiting id to 0 if(!size_queue) { trans_thread = 0; } //otherwise set transmit id variable to next in queue and dequeue that flow else { pthread_mutex_lock(&queue_mutex); trans_thread = nextQueue(); pthread_mutex_unlock(&queue_mutex); } pthread_mutex_unlock(&transmit); pthread_exit(NULL); }