Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #define INT_A 1 //spodny interval
- #define INT_B 30 //horny interval
- #define BUFF_SIZE 20 //pocet vygenerovanych cisel
- volatile int buffer[BUFF_SIZE];
- int loop;
- struct Data {
- volatile int index;
- pthread_mutex_t* mutex;
- pthread_cond_t* is_full;
- pthread_cond_t* not_full;
- };
- int checkfibonacci(int n) {
- int a,b,c,next;
- if((n==0)||(n==1))
- return 1;
- else
- {
- a=0;
- b=1;
- c=a+b;
- while(c<n)
- {
- a=b;
- b=c;
- c=a+b;
- }
- if(c==n)
- return 1;
- else
- return 0;
- }
- }
- void* produce (void* pdata){
- struct Data* data = (struct Data*) pdata;
- srand(time(NULL));
- while (loop < 150) {
- pthread_mutex_lock(data->mutex);
- if ((data->index + 1) == (BUFF_SIZE - 1)) {
- pthread_cond_wait(data->not_full, data->mutex);
- }
- data->index++;
- buffer[data->index] = rand()%(INT_B - INT_A);
- loop++;
- printf("Produce: %d \n", buffer[data->index]);
- //data->index++;
- pthread_mutex_unlock(data->mutex);
- pthread_cond_signal(data->is_full);
- }
- //return NULL;
- }
- void * consume (void* pdata){
- struct Data* data = (struct Data*) pdata;
- while (loop < 150) {
- pthread_mutex_lock(data->mutex);
- if ((data->index - 1) < 0) {
- pthread_cond_wait(data->is_full, data->mutex);
- }
- if (checkfibonacci(buffer[data->index]) == 1) {
- printf("JE: %d \n", buffer[data->index]);
- data->index--;
- } else {
- printf("NIE JE: %d \n", buffer[data->index]);
- data->index--;
- }
- //printf("index: %d \n",data->index);
- loop++;
- pthread_mutex_unlock(data->mutex);
- pthread_cond_signal(data->not_full);
- }
- //return NULL;
- }
- int main(void){
- loop = 0;
- pthread_mutex_t mutex;
- pthread_mutex_init(&mutex,NULL);
- pthread_cond_t cond1, cond2;
- pthread_cond_init(&cond1,NULL);
- pthread_cond_init(&cond2, NULL);
- struct Data data = {-1, &mutex, &cond1, &cond2};
- pthread_t thread1, thread2;
- pthread_create(&thread1,NULL,&produce,&data);
- pthread_create(&thread2,NULL,&consume,&data);
- pthread_join(thread1,NULL);
- pthread_join(thread2,NULL);
- pthread_mutex_destroy(&mutex);
- pthread_cond_destroy(&cond1);
- pthread_cond_destroy(&cond2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement