Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <semaphore.h>
- #include <pthread.h>
- #include <time.h>
- #include <stdlib.h>
- sem_t read_s, write_s;
- int g_buffer[3] = {0,0,0};
- int w_counter = 0;
- int r_counter = 0;
- //val : 1<=random <= 100
- int randomize(){
- return rand()%100 + 1;
- }
- void * construire_m(void* arg){
- int cpt = 0, val = 0;
- for(cpt = 0; cpt<30; cpt++){
- //generation de la val random
- val = randomize();
- sem_wait(&write_s);
- //write
- g_buffer[w_counter] = val;
- printf("W: [%d] = %d\n", w_counter,g_buffer[w_counter] );
- sem_post(&read_s);
- w_counter = (w_counter +1) % 3;
- }
- pthread_exit(NULL);
- }
- void * consommer_m(void* arg){
- int cpt = 0;
- for(cpt = 0; cpt<30; cpt++){
- sem_wait(&read_s);
- //read
- printf("R: [%d] = %d\n", r_counter, g_buffer[r_counter]);
- sem_post(&write_s);
- r_counter = (r_counter +1) % 3;
- }
- pthread_exit(NULL);
- }
- int main(int argc, char *argv[])
- {
- int iCtr = 0;
- pthread_t t_write, t_read;
- printf("[+] Initialisation \n");
- //initialisation des semaphores
- sem_init(&read_s , 0, 0);
- sem_init(&write_s, 0, 3);
- //initialisation du seed de rand
- srand(time(NULL));
- printf("[+] Trace : \n");
- //creation des thread
- if(pthread_create(&t_write, NULL,construire_m, NULL))
- {
- printf("Impossible de créer le thread d'ecriture\n");
- exit(1);
- }
- if(pthread_create(&t_read, NULL,consommer_m, NULL))
- {
- printf("Impossible de créer le thread de lecture\n");
- exit(1);
- }
- printf("[+] Threads created\n");
- pthread_join(t_read,NULL);
- pthread_join(t_write,NULL);
- //creation des thread
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement