Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <assert.h>
- #include <ctype.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <sys/time.h>
- #include <string.h>
- #include <stdint.h>
- #include "job_queue.h"
- pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
- pthread_cond_t nothing = PTHREAD_COND_INITIALIZER;
- pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
- pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
- int job_queue_init(struct job_queue *job_queue, int capacity) {
- job_queue->max_capacity = capacity;
- job_queue->rear = 0;
- job_queue->front = 0;
- job_queue->buffer = malloc(sizeof(void*) * capacity);
- job_queue->available = capacity;
- job_queue->destroy = 0;
- return 0;
- }
- int job_queue_destroy(struct job_queue *job_queue) {
- pthread_mutex_lock(&m);
- while (job_queue->available > 0){
- job_queue->destroy = 1;
- pthread_cond_broadcast(&fill);
- pthread_cond_wait(&empty, &m);
- }
- free(job_queue->buffer);
- pthread_mutex_unlock(&m);
- return 0;
- }
- int job_queue_push(struct job_queue *job_queue, void *data) {
- printf("hej \n");
- pthread_mutex_lock(&m);
- while (job_queue->available == 0 )
- {
- printf("hej2 \n");
- pthread_cond_wait(&empty, &m);
- printf("hej3 \n");
- }
- job_queue->buffer[job_queue->rear] = data;
- job_queue->available--;
- job_queue->rear ++;
- job_queue->rear = job_queue->rear % job_queue->max_capacity ;
- assert(pthread_cond_signal(&fill) == 0);
- pthread_mutex_unlock(&m);
- return 0;
- }
- int job_queue_pop(struct job_queue *job_queue, void **data) {
- printf("hejpop \n");
- pthread_mutex_lock(&m);
- printf("hejpop2 \n");
- while (job_queue->available == job_queue->max_capacity)
- {
- if (job_queue->destroy == 1) {
- return -1;
- }
- printf("hejpop3 \n");
- pthread_cond_wait(&fill, &m);
- }
- data[0] = job_queue->buffer[job_queue->front];
- job_queue->available ++;
- job_queue->front ++;
- job_queue->front = job_queue->front % job_queue->max_capacity;
- printf("hejpop4 \n");
- assert(pthread_cond_signal(&empty) == 0);
- pthread_mutex_unlock(&m);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement