Advertisement
minh_tran_782

Queue_Process_OS

Mar 13th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1.  
  2. #include <stdlib.h>
  3. #include "queue.h"
  4. #include <pthread.h>
  5.  
  6. /* Remember to initilize the queue before using it */
  7. void initialize_queue(struct pqueue_t * q) {
  8.     q->head = q->tail = NULL;
  9.     pthread_mutex_init(&q->lock, NULL);
  10. }
  11. // PCB = process control block
  12. /* Return non-zero if the queue is empty */
  13. int empty(struct pqueue_t * q) {
  14.     return (q->head == NULL);
  15. }
  16.  
  17. /* Get PCB of a process from the queue (q).
  18.  * Return NULL if the queue is empty */
  19. struct pcb_t * de_queue(struct pqueue_t * q) {
  20.     struct pcb_t * proc = NULL;
  21.  
  22.     // TODO: return q->head->data and remember to update the queue's head
  23.     // and tail if necessary. Remember to use 'lock' to avoid race
  24.     // condition
  25.     // YOUR CODE HERE
  26.         if (q->head == NULL) return NULL;
  27.     pthread_mutex_lock(&q->lock);
  28.    
  29.     proc = (struct pcb_t *) malloc(sizeof(struct pcb_t));
  30.    
  31.     proc->arrival_time = q->head->data->arrival_time;
  32.     proc->burst_time = q->head->data->burst_time;
  33.     proc->pid = q->head->data->pid;
  34.    
  35.     struct qitem_t* ptr = q->head;
  36.     struct pcb_t* ptr_data = q->head->data;  
  37.    
  38.     q->head = q->head->next;
  39.  
  40.     if (q->head == NULL) q->tail = NULL;
  41.    
  42.     free(ptr_data);
  43.     free(ptr);
  44.  
  45.     pthread_mutex_unlock(&q->lock);    
  46.     return proc;
  47. }
  48.  
  49. /* Put PCB of a process to the queue. */
  50. void en_queue(struct pqueue_t * q, struct pcb_t * proc) {
  51.     // TODO: Update q->tail.
  52.     // Remember to use 'lock' to avoid race condition
  53.    
  54.     // YOUR CODE HERE
  55.        
  56.     if (q->head == NULL)
  57.     {
  58.         pthread_mutex_lock(&q->lock);
  59.        
  60.         struct qitem_t *newNode = (struct qitem_t* )malloc(sizeof(struct qitem_t));
  61.        
  62.         newNode->data  = proc;
  63.         newNode->next = NULL;
  64.        
  65.         q->head = newNode;
  66.         q->tail = newNode;
  67.        
  68.         pthread_mutex_unlock(&q->lock);
  69.        
  70.         return;
  71.     }
  72.         pthread_mutex_lock(&q->lock);
  73.         struct qitem_t *newNode = (struct qitem_t*)malloc(sizeof(struct qitem_t));
  74.        
  75.         newNode->data  = proc;
  76.         newNode->next = NULL;
  77.        
  78.         q->tail->next = newNode;
  79.         q->tail = newNode;
  80.         pthread_mutex_unlock(&q->lock);
  81.         return;
  82. }
  83.  
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement