Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Antonis Mpelantis 3583*/
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <semaphore.h>
- #include <time.h>
- #include <unistd.h>
- pthread_mutex_t mutex0, mutex1, mutex2;
- pthread_t chef, cooks[3];
- int materials[3] = {0, 0, 0}; //materials[0] = meat, materials[1] = potatoes, materials[2] = pita
- //Function used from chef to select the materials
- void select_materials(){
- int random[2];
- int i = (rand() % (2 - 0 + 1)) + 0, z;
- materials[i]++;
- while(1){
- z = (rand() % (2 - 0 + 1)) + 0;
- if(z != i){
- materials[z]++;
- break;
- }
- }
- }
- void createANDconsume(){
- printf("Finishing and consuming the meal.\n");
- materials[0] == 0;
- materials[1] == 0;
- materials[2] == 0;
- sleep(2);
- }
- void *cook_function(void *t){
- pthread_mutex_lock(&mutex1);
- int i;
- for(i = 0; i < 3; i++){
- printf("\n\n materiala %d: %d", i , materials[i]);
- }
- if(materials[0] == 0){
- printf("Chef added potatoes and pita.\n");
- materials[0]++;
- printf("Cook 0 added meat.\n");
- createANDconsume();
- printf("The meal is over.\n\n");
- }
- else if(materials[1] == 0){
- printf("Chef added meat and pita.\n");
- materials[1]++;
- printf("Cook 1 added potatoes.\n");
- createANDconsume();
- printf("The meal is over.\n\n");
- }
- else if(materials[2] == 0){
- printf("Chef added meat and potatoes.\n");
- materials[2]++;
- printf("Cook 2 added pita.\n");
- createANDconsume();
- printf("The meal is over.\n\n");
- }
- printf("\n\n materialb %d: %d", 0 , materials[0]);
- printf("\n\n materialb %d: %d", 1 , materials[1]);
- printf("\n\n materialb %d: %d", 2 , materials[2]);
- pthread_mutex_unlock(&mutex1);
- }
- void *chef_function(void *t){
- while(1){
- pthread_mutex_lock(&mutex0);
- int i;
- select_materials();
- if(materials[0] == 0){
- pthread_join(cooks[0], NULL);
- }
- else if(materials[1] == 0){
- pthread_join(cooks[1], NULL);
- }
- else if(materials[2] == 0){
- pthread_join(cooks[2], NULL);
- }
- pthread_mutex_unlock(&mutex0);
- }
- }
- int main(){
- pthread_mutex_init(&mutex1, NULL);
- int i, c_thread;
- for(i = 0; i < 3; i++){
- c_thread = pthread_create(&(cooks[i]), NULL, &cook_function, NULL);
- }
- // pthread_mutex_destroy(&mutex1);
- pthread_mutex_init(&mutex0, NULL);
- c_thread = pthread_create(&chef, NULL, &chef_function, NULL);
- int j_thread;
- j_thread = pthread_join(chef, NULL);
- // pthread_mutex_destroy(&mutex0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement