Advertisement
AntonioVillanueva

Ejemplo de 2 Threads en C

Jul 26th, 2019
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <unistd.h>
  3. #include <pthread.h>
  4. #include <stdio.h>
  5. //gcc main.c -o monProgramme -lpthread
  6.  
  7. void* thread2 (void* arg);
  8. void* thread1 (void* arg);
  9.  
  10. int main (void)
  11. {
  12.     int val=0;
  13.     pthread_t monthread1;
  14.     pthread_t monthread2;
  15.  
  16.     pthread_create (&monthread1, NULL, thread1, &val);
  17.     pthread_create (&monthread2, NULL, thread2, &val); /* Création des threads */
  18.  
  19.     pthread_join (monthread1, NULL);
  20.     pthread_join (monthread2, NULL); /* Attente de la fin des threads */
  21.    
  22.     printf ("val =%d\n",val);
  23.  
  24.     return 0;
  25. }
  26.  
  27. void* thread1 (void* arg)
  28. {
  29.     int *val = arg;
  30.     printf ("thread1 ON \n");
  31.     for (int i=0;i<100;i++){
  32.         (*val)++;
  33.     }
  34.    
  35.     printf ("thread1 OFF \n"); 
  36.     pthread_exit(NULL); /* Fin du thread */
  37. }
  38.  
  39. void* thread2 (void* arg)
  40. {
  41.     int *val = arg;
  42.     printf ("thread2 ON \n");  
  43.     for (int i=0;i<100;i++){
  44.         (*val)++;
  45.     }
  46.    
  47.     printf ("thread2 OFF \n"); 
  48.     pthread_exit(NULL); /* Fin du thread */
  49.    
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement