Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <errno.h>
- #include <sys/types.h>
- #define CANS 2
- #define CLIENTS 6
- void * func (void * arg_wsk);
- struct pub {int cansTab[CANS]; pthread_mutex_t* mutex; pthread_mutex_t* mutex2;};
- static int threadNumber= 0;
- int main(){
- pthread_mutex_t mutex, mutex2;
- struct pub pub1;
- pub1.mutex = &mutex;
- pub1.mutex2 = &mutex2;
- int i;
- for(i=0; i<CANS; i++)
- pub1.cansTab[i] = 1;
- pthread_t tid[CLIENTS];
- for(i=0; i < CLIENTS; i++)
- {
- pthread_create(&tid[i], NULL, func, &pub1);
- }
- for(i=0; i < CLIENTS; i++)
- {
- pthread_join(tid[i],NULL);
- }
- }
- void * func (void * arg_wsk){
- struct pub *pub_wsk = arg_wsk;
- int thread_nr = threadNumber++;
- int i, canNr, useCanNr;
- for(i=0;i<2;i++)
- {
- printf("Klient %d: chcialby wypic %d piwo \n", thread_nr, 1+i);
- while(1)
- {
- {
- if(pthread_mutex_trylock(&pub_wsk->mutex[canNr%CANS])==0)
- {
- useCanNr = canNr%CANS;
- break;
- }
- else { canNr++; }
- }
- pthread_mutex_lock(pub_wsk->mutex2);
- usleep(500);
- pthread_mutex_unlock(pub_wsk->mutex2);
- printf("Klient %d: ma kufel. Pije %d piwo z %d kufla \n", thread_nr, i+1, useCanNr+1);
- usleep(2500);
- printf("Klient %d: wypił %d piwo. Odklada %d kufel \n", thread_nr, i+1, useCanNr+1);
- pthread_mutex_unlock (&pub_wsk->mutex[useCanNr]);
- }
- return(NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement