Last active
April 2, 2017 12:55
-
-
Save ahmedengu/1d313b8500ea55a46f2cc24defbacb0f to your computer and use it in GitHub Desktop.
2 producer 1 consumer semaphore
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; | |
for (i = 0; i < number; ++i) { | |
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; | |
for (i = 0; i < number; ++i) { | |
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; | |
for (i = 0; i < number; ++i) { | |
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_join(t[0], NULL); | |
pthread_join(t[1], NULL); | |
pthread_join(t[2], NULL); | |
sem_destroy(&full_sem); | |
sem_destroy(&empty_sem); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment