Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <pthread.h>
  9.  
  10. #include "debug.h"
  11. #include "memory.h"
  12. #include "args.h"
  13.  
  14. void *task(void *arg);
  15.  
  16. #define NUM_THREADS 200
  17. #define NUM_INCREMENTOS 1000
  18.  
  19. typedef struct thread_params_t
  20. {
  21.     pthread_mutex_t mutex;
  22. }thread_params_t;
  23.  
  24. int G_shared_counter;
  25.  
  26. int main(int argc, char *argv[]){
  27.  
  28.     (void)argc; (void)argv;
  29.  
  30.     G_shared_counter = 0;
  31.  
  32.     pthread_t tids[NUM_THREADS];
  33.     thread_params_t thread_params;
  34.  
  35.     // Mutex: inicializa o mutex antes de criar a(s) thread(s) 
  36.     if ((errno = pthread_mutex_init(&thread_params.mutex, NULL)) != 0)
  37.         ERROR(12, "pthread_mutex_init() failed");
  38.    
  39.     // Criação das threads + passagem de parâmetro
  40.     for (int i = 0; i < NUM_THREADS; i++){
  41.         if ((errno = pthread_create(&tids[i], NULL, task, &thread_params)) != 0)
  42.             ERROR(10, "Erro no pthread_create()!");
  43.     }
  44.  
  45.     // Espera que todas as threads terminem
  46.     for (int i = 0; i < NUM_THREADS; i++){
  47.         if ((errno = pthread_join(tids[i], NULL)) != 0)
  48.             ERROR(11, "Erro no pthread_join()!\n");
  49.     }
  50.  
  51.     // Mutex: liberta recurso
  52.     if ((errno = pthread_mutex_destroy(&thread_params.mutex)) != 0)
  53.         ERROR(13, "pthread_mutex_destroy() failed");
  54.  
  55.     printf("G_shared_counter = %d\n", G_shared_counter);
  56.  
  57.     return 0;
  58. }
  59.  
  60. void *task(void *arg)
  61. {
  62.     // cast para o tipo de dados enviado pela 'main thread'
  63.     struct thread_params_t *params = (struct thread_params_t *) arg;
  64.     int local;
  65.  
  66.     // Mutex: entra na secção crítica
  67.     if ((errno = pthread_mutex_lock(&params->mutex)) != 0){    
  68.         WARNING("pthread_mutex_lock() failed");
  69.         return NULL;
  70.     }
  71.  
  72.     for (int i = 0; i < NUM_INCREMENTOS; ++i)
  73.     {
  74.         local = G_shared_counter;
  75.         sched_yield();
  76.         local = local + 1;
  77.         G_shared_counter = local;
  78.     }
  79.  
  80.     if ((errno = pthread_mutex_unlock(&params->mutex)) != 0){
  81.         WARNING("pthread_mutex_unlock() failed");
  82.         return NULL;
  83.     }
  84.    
  85.     return NULL;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement