Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Si realizzi un programma in C e Posix sotto Linux che , con l ausilio della libreria pthread , lancia n thread passato da riga di comando , in modo che il thread i-esimo prelevi casualmente un elemento da una matrice m * n di cartteri allocata dinamicamente e lo insersca in un buffer circolare di grandezza N.
- Concorrentemente agli n thread , un thread n+1 esimo , preleva continuamente un elemento disponibile , e lo stampa.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <time.h>
- #include <semaphore.h>
- char ** matrix, *array ;
- int m,N,index_produttore = 0;
- long int n;
- sem_t mutex,size_N,event;
- void print_matrix(int row, int col){
- int i, j;
- for(i=0;i<row;i++){
- printf("\n");
- for(j=0;j<col;j++){
- printf("%c ",matrix[i][j]);
- }
- }
- }
- void set_matrix(int row, int col){
- int i, j;
- for(i=0;i<row;i++){
- for(j=0;j<col;j++){
- matrix[i][j] = 65 + rand() %(90-65);
- }
- }
- }
- void * insert(void * args ){
- int index = (* (int *) args);
- int index_row_rand,index_col_rand;
- index_row_rand = rand()%m;
- index_col_rand = rand()%n;
- sem_wait(&size_N);
- sem_wait(&mutex);
- array[index_produttore % N] = matrix[index_row_rand][index_col_rand];
- index_produttore ++;
- printf("\ni m thread %lu value of index_row rand : %d ,value of index_col_rand %d, index array %d , value array[%c]\n ",pthread_self(),index_row_rand, index_col_rand,index_produttore,matrix[index_row_rand][index_col_rand]);
- sem_post(&mutex);
- sem_post(&event);
- return (NULL);
- }
- void * cons(void * args){
- int i;
- for(i=0;i<n;i++){
- sem_wait(&event);
- sem_wait(&mutex);
- printf("consumer this is value of buffer[%d] %c\n",i,array[i % N]);
- sem_post(&mutex);
- sem_post(&size_N);
- }
- return(NULL);
- }
- void main(int argc, char *argv[]){
- if ( argc != 4 ){
- fprintf(stderr,"error pass two argument \n");
- fprintf(stderr,"pass size row , size of column, size of array\n");
- exit(-1);
- }
- srand(time(NULL));
- m = atoi(argv[1]);
- n = atoi(argv[2]);
- N = atoi(argv[3]);
- int task[N],i;
- pthread_t * tid, consumer;
- matrix = malloc( sizeof(int *) * m );
- array = malloc( sizeof(int) * N);
- tid = malloc( sizeof(pthread_t) * n );
- for(i=0;i<m;i++)
- matrix[i] = malloc( sizeof (int) * n);
- set_matrix(m,n);
- print_matrix(m,n);
- sem_init(&mutex,0,1);
- sem_init(&event,0,0);
- sem_init(&size_N,0,N);
- for(i=0;i<n;i++){
- task[i] = i;
- pthread_create(&tid[i],NULL,insert,&task[i]);
- }
- pthread_create(&consumer,NULL,cons,NULL);
- for(i=0;i<n;i++)
- pthread_join(tid[i],NULL);
- pthread_join(consumer,NULL);
- sem_destroy(&mutex);
- sem_destroy(&event);
- sem_destroy(&size_N);
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement