Jeremiah_

SO 4-threads

Oct 22nd, 2018
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <conio.h>
  5. #include <windows.h>
  6.  
  7. //Variável acessível pelos dois threads e pela função main
  8. char a = 'a';
  9. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  10. //função do thread 1
  11. void* threadFunction(void* args)
  12. {
  13.     int n = 5;
  14.     while(n--)
  15.     {
  16.         pthread_mutex_lock( &mutex );
  17.  
  18.         printf("Estou em threadFunction\nvar a == %c\n", a++);
  19.         pthread_mutex_unlock( &mutex );
  20.     }
  21. }
  22.  
  23. //função do thread 2
  24. void* threadFunction2(void* args)
  25. {
  26.     int n = 3;
  27.     while(n--)
  28.     {
  29.         pthread_mutex_lock( &mutex );
  30.  
  31.         printf("Estou em threadFunction2\nvar a == %c\n", a++);
  32.         pthread_mutex_unlock( &mutex );
  33.     }
  34. }
  35.  
  36. int main()
  37. {
  38.     //thread id
  39.     pthread_t tid1, tid2;
  40.     int tRet;
  41.  
  42.     //criando thread 1
  43.     tRet = pthread_create(&tid1, NULL, &threadFunction, NULL);
  44.  
  45.     //Teste para saber se foi criado com sucesso ou não
  46.     if (tRet) {
  47.         printf("Thread1 fail!\n");
  48.         return 0; /*return from main*/
  49.     }
  50.  
  51.     //criando thread 2
  52.     tRet = pthread_create(&tid2, NULL, &threadFunction2, NULL);
  53.  
  54.     if (tRet) {
  55.         printf("Thread2 fail!\n");
  56.         return 0; /*return from main*/
  57.     }
  58.  
  59.     //barreira de threads
  60.     pthread_join(tid1, NULL);
  61.     pthread_join(tid2, NULL);
  62.  
  63.     exit (0);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment