Created
March 12, 2014 21:46
-
-
Save ababol/9517082 to your computer and use it in GitHub Desktop.
Ring, consumer/producer problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "ring.h" | |
void ring_init(Ring* r, int size) { | |
r->data = malloc(sizeof(int)*size); | |
r->capacity = size; | |
r->actualSize = 0; | |
r->write_cursor = 0; | |
r->read_cursor = 0; | |
pthread_mutex_init(&r->lock, NULL); | |
pthread_cond_init(&r->cond_no_more_empty, NULL); | |
} | |
int ring_push(Ring* r, int i) { | |
pthread_mutex_lock(&r->lock); | |
if (r->read_cursor==r->write_cursor && r->actualSize != 0) { | |
pthread_mutex_unlock(&r->lock); | |
return -2; | |
} | |
r->data[r->write_cursor] = i; | |
r->actualSize++; | |
r->write_cursor++; | |
if (r->write_cursor >= r->capacity) r->write_cursor = 0; | |
pthread_cond_signal(&r->cond_no_more_empty); // reveille le while (r->actualSize==0) | |
pthread_mutex_unlock(&r->lock); | |
return 1; | |
} | |
void ring_destroy(Ring* r) { | |
free(r->data); | |
free(r); | |
} | |
int ring_pop(Ring* r) { | |
pthread_mutex_lock(&r->lock); | |
while (r->actualSize==0) { | |
pthread_cond_wait(&r->cond_no_more_empty, &r->lock); | |
} | |
int number; | |
number = r->data[r->read_cursor]; | |
r->actualSize--; | |
r->read_cursor++; | |
if (r->read_cursor >= r->capacity) r->read_cursor = 0; | |
pthread_mutex_unlock(&r->lock); | |
return number; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef RING_H | |
#define RING_H | |
#include <pthread.h> | |
#include <stdlib.h> | |
typedef struct { | |
int* data; | |
int actualSize; | |
int capacity; | |
int write_cursor; | |
int read_cursor; | |
pthread_mutex_t lock; | |
pthread_cond_t cond_no_more_empty; | |
} Ring; | |
void ring_init(Ring* r, int size); | |
int ring_push(Ring* r, int i); | |
void ring_destroy(Ring* r); | |
int ring_pop(Ring* r); | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment