Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <time.h>
- #include <pthread.h>
- void* clientThread (void* arg);
- int freeMugs = 0;
- int beersDrank = 0;
- int freeTaps = 0;
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- void* clientThread(void* arg) {
- int id = *((int*) arg);
- int i, tap, mug;
- int beers = 5;
- printf("[Klient %d]: Wejscie do pubu!\n", id);
- for (i = 0; i < beers; i++) {
- printf("FREE MUGS: %d \n", freeMugs);
- // SEKCJA KRYTYCZNA
- while(1) {
- pthread_mutex_lock(&mutex);
- if (freeMugs > 0) {
- freeMugs--; // ZAJECIE KUFLA
- // OPUSZCZENIE SEKCJI KRYTYCZNEJ
- pthread_mutex_unlock(&mutex);
- break;
- } else {
- pthread_mutex_unlock(&mutex);
- }
- }
- tap = 0;
- printf("[Klient %d]: Nalanie piwa z kranu %d!\n", id, tap);
- usleep(300);
- beersDrank++;
- printf("[Klient %d]: WYPICIE PIWA!\n", id);
- nanosleep((struct timespec[]){{0, 500000000L}}, NULL);
- printf("[Klient %d]: Zwrot kufla!\n", id);
- pthread_mutex_lock(&mutex);
- freeMugs++; // ZWROT KUFLA DO PULI
- pthread_mutex_unlock(&mutex);
- }
- printf("[Klient %d]: Wyjscie z pubu!\n", id);
- return(NULL);
- }
- main () {
- pthread_t* client;
- int* clientId;
- int clientsCount, mugsCount, tapsCount, i;
- // Initial data
- printf("\nLiczba klientow: "); scanf("%d", &clientsCount);
- printf("\nLiczba kufli: "); scanf("%d", &mugsCount);
- tapsCount = 3;
- // Spawn clients
- client = (pthread_t*) malloc(clientsCount * sizeof(pthread_t));
- clientId = (int*) malloc(clientsCount * sizeof(int));
- for (i = 0; i < clientsCount; i++) clientId[i] = i;
- // Start
- printf("Pub zostal otwarty!\n");
- freeMugs = mugsCount;
- freeTaps = tapsCount;
- printf("W pubie zostalo %d wolnych kufli!\n", freeMugs);
- for (i = 0; i < clientsCount; i++) {
- pthread_create(&client[i], NULL, clientThread, &clientId[i]);
- }
- for(i = 0; i < clientsCount; i++){
- pthread_join(client[i], NULL);
- }
- printf("DZISIAJ WYPITO %d KUFLI!\n", beersDrank);
- printf("Pub zostal zamkniety!\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement