Last active
May 29, 2016 15:14
-
-
Save ahmedengu/502a026be09e7ba27d95684819be8fe4 to your computer and use it in GitHub Desktop.
2 producer 1 consumer // Running here: http://ideone.com/N83BRQ
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 <pthread.h> | |
#include <semaphore.h> | |
#include <math.h> | |
#include <ctype.h> | |
#define NUM 15 | |
int number = NUM, buff = 0; | |
char queue[NUM][NUM]; | |
sem_t full_sem, empty_sem; | |
void insert(char e[]) { | |
if (buff + 1 < number) { | |
buff++; | |
printf(", inserted text: %s", e); | |
int i = 0; | |
for (i = 0; i < number; ++i) { | |
queue[buff][i] = e[i]; | |
} | |
} else { | |
printf("\nfull"); | |
} | |
} | |
void *produce2() { | |
int i = 0; | |
sem_wait(&full_sem); | |
printf("\nP2:: insert random text #%d", i); | |
char tmpChar[number]; | |
int j = 0; | |
for (j = 0; j < number; ++j) { | |
tmpChar[j] = (char) 'a' + (random() % 26); | |
} | |
insert(tmpChar); | |
sem_post(&empty_sem); | |
} | |
void *produce() { | |
int i = 0; | |
sem_wait(&full_sem); | |
printf("\nP1:: insert random text #%d", i); | |
char tmpChar[number]; | |
int j = 0; | |
for (j = 0; j < number; ++j) { | |
tmpChar[j] = (char) 'a' + (random() % 26); | |
} | |
insert(tmpChar); | |
sem_post(&empty_sem); | |
} | |
void *consume(void *a) { | |
int i = 0; | |
char v[number]; | |
sem_wait(&empty_sem); | |
if (buff > 0) { | |
int j = 0; | |
for (j = 0; j < number; ++j) { | |
v[j] = toupper(queue[buff][j]); | |
} | |
buff--; | |
} else { | |
printf("\nempty"); | |
} | |
printf("\nuppercase char: %s", v); | |
sem_post(&full_sem); | |
} | |
int main() { | |
pthread_t t[3]; | |
sem_init(&full_sem, 0, number - 1); | |
sem_init(&empty_sem, 0, 0); | |
pthread_create(&t[0], NULL, &produce, NULL); | |
pthread_create(&t[1], NULL, &produce2, NULL); | |
pthread_create(&t[2], NULL, &consume, NULL); | |
pthread_create(&t[2], NULL, &consume, NULL); | |
pthread_join(t[0], NULL); | |
pthread_join(t[1], NULL); | |
pthread_join(t[2], NULL); | |
sem_destroy(&full_sem); | |
sem_destroy(&empty_sem); | |
return 0; | |
} |
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
// output from : http://ideone.com/N83BRQ | |
P2:: insert random text #0, inserted text: nwlrbbmqbhcdarz | |
uppercase char: NWLRBBMQBHCDARZ | |
P1:: insert random text #0, inserted text: owkkyhiddqscdxr | |
uppercase char: OWKKYHIDDQSCDXR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment