Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <semaphore.h>
- #define K 10
- #define N 20
- /*semafori globali*/
- sem_t A, B, C;
- /*dichiaro la struttura globale dei thread*/
- struct thread{
- int ID;
- int tipo;
- };
- /*dichiaro le funzioni*/
- void *elabora1(void *);
- void elabora2(struct thread);
- int esito(struct thread);
- int main()
- {
- /*inizializzo le variabili*/
- int i=0;
- int tipo;
- pthread_t thread_id[1000]; //mi servirà poi per attendere che finiscano tutti
- //i thread prima di terminare il main
- struct thread thRd[1000];
- /*inizializzo i semafori*/
- sem_init(&A, 0, K);
- sem_init(&B, 0, 1);
- sem_init(&C, 0, 1);
- //creo a random il tipo di thread
- while(i<N){
- thRd[i].ID=i;
- thRd[i].tipo=rand()%2;
- pthread_create(&thread_id[i], NULL, &elabora1, &thRd[i]);
- printf("\nThread n: %d creato", i); i++; sleep(5);}
- i=0;
- while(i<N){
- pthread_join(thread_id[i], NULL);
- i++;}
- printf("\n\n");
- }
- /*definisco le funzioni*/
- void *elabora1(void *p)
- {
- struct thread *thr=p;
- if(thr->tipo==0){
- /*Sezione critica*/
- sem_wait(&A);
- /*Elaborazione*/
- printf("\nThread n: %d sta usando la risorsa A", thr->ID);
- sleep(3);
- /*fine sezione critica*/
- sem_post(&A);}
- else{
- /*sezione critica*/
- sem_wait(&A);
- sem_wait(&B);
- /*Elaborazione*/
- printf("\nThread n: %d sta usando le risorse A e B", thr->ID);
- sleep(5);
- /*invoco esito*/
- if(esito(*thr)==0){
- /*fine sezione critica*/
- sem_post(&A);
- sem_post(&B);}
- else{
- elabora2(*thr);
- sem_post(&A);
- sem_post(&B);}}
- printf("\nIl thread n: %d ha terminato l'elaborazione", thr->ID);
- }
- int esito(struct thread thr)
- {
- /*Elaborazione*/
- printf("\nThread n: %d sta elaborando l'esito", thr.ID);
- sleep(5);
- return (rand() %2);
- }
- void elabora2(struct thread thr)
- {
- sem_wait(&C);
- /*Elaborazione*/
- printf("\nThread n: %d sta usando la risorsa C", thr.ID);
- sleep(3);
- sem_post(&C);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement