Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <assert.h>
  4.  
  5. #include <ctype.h>
  6. #include <unistd.h>
  7. #include <pthread.h>
  8. #include <sys/time.h>
  9. #include <string.h>
  10. #include <stdint.h>
  11.  
  12. #include "job_queue.h"
  13.  
  14.  
  15. pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
  16. pthread_cond_t nothing = PTHREAD_COND_INITIALIZER;
  17. pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
  18. pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
  19.  
  20. int job_queue_init(struct job_queue *job_queue, int capacity) {
  21. job_queue->max_capacity = capacity;
  22. job_queue->rear = 0;
  23. job_queue->front = 0;
  24. job_queue->buffer = malloc(sizeof(void*) * capacity);
  25. job_queue->available = capacity;
  26. job_queue->destroy = 0;
  27. return 0;
  28. }
  29.  
  30. int job_queue_destroy(struct job_queue *job_queue) {
  31. pthread_mutex_lock(&m);
  32. while (job_queue->available > 0){
  33. job_queue->destroy = 1;
  34. pthread_cond_broadcast(&fill);
  35. pthread_cond_wait(&empty, &m);
  36. }
  37. free(job_queue->buffer);
  38. pthread_mutex_unlock(&m);
  39. return 0;
  40. }
  41.  
  42. int job_queue_push(struct job_queue *job_queue, void *data) {
  43. printf("hej \n");
  44. pthread_mutex_lock(&m);
  45. while (job_queue->available == 0 )
  46. {
  47. printf("hej2 \n");
  48. pthread_cond_wait(&empty, &m);
  49. printf("hej3 \n");
  50. }
  51. job_queue->buffer[job_queue->rear] = data;
  52. job_queue->available--;
  53. job_queue->rear ++;
  54. job_queue->rear = job_queue->rear % job_queue->max_capacity ;
  55. assert(pthread_cond_signal(&fill) == 0);
  56. pthread_mutex_unlock(&m);
  57. return 0;
  58.  
  59. }
  60.  
  61. int job_queue_pop(struct job_queue *job_queue, void **data) {
  62. printf("hejpop \n");
  63. pthread_mutex_lock(&m);
  64. printf("hejpop2 \n");
  65. while (job_queue->available == job_queue->max_capacity)
  66. {
  67. if (job_queue->destroy == 1) {
  68. return -1;
  69. }
  70. printf("hejpop3 \n");
  71. pthread_cond_wait(&fill, &m);
  72. }
  73. data[0] = job_queue->buffer[job_queue->front];
  74. job_queue->available ++;
  75. job_queue->front ++;
  76. job_queue->front = job_queue->front % job_queue->max_capacity;
  77. printf("hejpop4 \n");
  78. assert(pthread_cond_signal(&empty) == 0);
  79. pthread_mutex_unlock(&m);
  80. return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement